//主面板
WEBKP.namespace('MianPanel');
WEBKP.MianPanel = function(){
    this.mainObj = $("#mainpanel");
    this.selectFileIds = [];//选择的文件id
    this.selectFolderIds = [];//选择文件夹id
    this.checkAllSubject = '';
    this.selectType = '';
}
WEBKP.MianPanel.prototype = {
    updateSelectFile: function(type, id, checked){
        if (checked) {
            this.selectType = type;
            if (type == 'folder') {
                if ($.inArray(id, this.selectFolderIds) == -1) {
                    this.selectFolderIds.push(id);
                }
            }
            else {
                if ($.inArray(id, this.selectFileIds) == -1) {
                    this.selectFileIds.push(id);
                }
            }
        }
        else{
            if (type == 'folder') {
                var index = $.inArray(id, this.selectFolderIds);
                if (index != -1) {
                    this.selectFolderIds.splice(index, 1);
                }
            }
            else {
                var index = $.inArray(id, this.selectFileIds);
                if (index != -1) {
                    this.selectFileIds.splice(index, 1);
                }
            }
        }
    },
    getSelectType: function(){
        return this.selectType;
    },
    getSelectFile: function(){
        var fileNum = this.selectFileIds.length;
        var folderNum = this.selectFolderIds.length;
        return [fileNum, folderNum, folderNum + fileNum];//第一个文件，第二是文件夹，第三个是总数
    },
    getSelectFilesId: function(){
        var allFilesId = [];
        return $.merge($.merge(allFilesId, this.selectFileIds), this.selectFolderIds);
    },
    clearSelectFilesId: function(){
        this.selectFileIds = [];
        this.selectFolderIds = [];
    },
    getFileInfoByFileId: function(fileId){//根据fileId获取文件信息
        var observers = this.checkAllSubject.observers;//this is a arraylist
        if (observers) {
            for (var i = 0, len = observers.Count(); i < len; i++) {
                var observer = observers.GetAt(i);
                if (observer.fileId == fileId) {
                    return observer;
                }
            }
        }
    },
    getAllFiles: function(type)//获取所有 type='file' 文件 type='folder' 文件夹 情况返回所有
    {
        if (this.checkAllSubject) {
            var observers = this.checkAllSubject.observers;//this is a arraylist
            var getFiles = [], allFiles = [];
            if (observers) {
                for (var i = 0, len = observers.Count(); i < len; i++) {
                    var observer = observers.GetAt(i);
                    if (type) {
                        (observer.fileType == type) && getFiles.push(observer);
                    }
                    else {
                        allFiles.push(observer);
                    }
                }
            }
            return (getFiles.length == 0) ? allFiles : getFiles;
        }
        else {
            return [];
        }
    },
    refreshFilePanel: function(act, fileResult){//刷新文件面板
        var _this = this;
        switch (act) {
            case 'create':
            case 'move':
                for (var i = 0, len = fileResult.length; i < len; i++) {
                    var observersObj = MainPanelObj.getFileInfoByFileId(fileResult[i]);
                    MainPanelObj.checkAllSubject.RemoveObserver(observersObj);
                    $("#tr" + fileResult[i]).remove();
                }
                _this.clearSelectFilesId();
                CreateMenu();
                break;
            case 'delete':
                if(typeof isShowDel!= 'undefined'&&'1'==isShowDel)
                {
                    for (var i = 0, len = fileResult.length; i < len; i++) {
                        var observersObj = MainPanelObj.getFileInfoByFileId(fileResult[i]);
                        observersObj.isdel = '1';
                        MainPanelObj.checkAllSubject.RemoveObserver(observersObj);
                        MainPanelObj.checkAllSubject.AddObserver(observersObj);
                        $("#tr" + fileResult[i]).attr('isdel','1');
                        $.each($("#tr" + fileResult[i]).find('td:gt(0)'),function(i, n){
                            if(0==i)
                            {
                                $(n).html("<del class='rel gray-2'>"+$(n).html()+"</del>").find('a').addClass('gray-2');
                            }else
                            {
                                $(n).html("<del class='gray-2'>"+$(n).html()+"</del>");
                            }
                        });
                    }
                    loadFileCallBack($("#filelistwrap"));
                    //CreateMenu();
                }else//正常删除
                {
                    for (var i = 0, len = fileResult.length; i < len; i++) {
                        var observersObj = MainPanelObj.getFileInfoByFileId(fileResult[i]);
                        MainPanelObj.checkAllSubject.RemoveObserver(observersObj);
                        $("#tr" + fileResult[i]).remove();
                    }
                    _this.clearSelectFilesId();
                    CreateMenu();
                }
                break;
            case 'realdel':
                location.reload();
                break;
            case 'recove':
                if(typeof isShowDel!= 'undefined'&&'1'==isShowDel)
                {
                    location.reload();
                    //for (var i = 0, len = fileResult.length; i < len; i++) {
                    //    var observersObj = MainPanelObj.getFileInfoByFileId(fileResult[i]);
                    //    observersObj.isdel = 0;
                    //    MainPanelObj.checkAllSubject.RemoveObserver(observersObj);
                    //    MainPanelObj.checkAllSubject.AddObserver(observersObj);
                    //    $("#tr" + fileResult[i]).attr('isdel','0');
                    //    $.each($("#tr" + fileResult[i]).find('del'),function(i, n){
                    //        $(n).replaceWith($(n).html());
                    //    });
                    //}
                    //loadFileCallBack($("#filelistwrap"));
                }else//回收站
                {
                    for (var i = 0, len = fileResult.length; i < len; i++) {
                        var observersObj = MainPanelObj.getFileInfoByFileId(fileResult[i]);
                        MainPanelObj.checkAllSubject.RemoveObserver(observersObj);
                        $("#tr" + fileResult[i]).remove();
                    }
                    _this.clearSelectFilesId();
                    CreateMenu();
                }
                break;
            case 'rename':
                if ('ok' == fileResult.result) {
                    var observersObj = MainPanelObj.getFileInfoByFileId(fileResult.fileId);
                    observersObj.fileName = fileResult.fileName;
                    MainPanelObj.checkAllSubject.RemoveObserver(observersObj);
                    MainPanelObj.checkAllSubject.AddObserver(observersObj);
                    $("#tr" + fileResult.fileId).attr('fileName', fileResult.fileName).find('a').html(CommFormatFileName(fileResult.fileName,20,3));
                }
                break;
            case 'upload'://上传刷新[{'fileName','
                $("#filelistwrap").prepend(fileResult);
                loadFileCallBack($("#filelistwrap"));
                break;
            case 'share'://共享刷新
                $.ajax({
                    url:'index.php?ac=fileview_handler&op=getiteminfo',
                    dataType:'json',
                    data:{fileId:fileResult.fileId},
                    type:'post',
                    success:function(res)
                    {
                        if(res&&res.xLive_attr&&'ok' == res.xLive_attr.result)
                        {
                            var trObj = $('#tr'+fileResult.fileId);
                            var observersObj = MainPanelObj.getFileInfoByFileId(fileResult.fileId);
                            if('0' == res.xLive.shareId)
                            {
                                observersObj.shareId = '0';
                                trObj.find('.ico-share-out').remove();
                            }else
                            {
                                observersObj.shareId = fileResult.fileId;
                                trObj.find('a').before('<b title="已共享" class="ico ico-share-out "></b>');
                            }
                            MainPanelObj.checkAllSubject.RemoveObserver(observersObj);
                            MainPanelObj.checkAllSubject.AddObserver(observersObj);
                            CreateMenu();
                        }
                    }
                })
                break;
            default:
                location.reload();
        }
    },
    scroolTop: function(){
        this.mainObj.scrollTop(0);
    }
}
var MainPanelObj = new WEBKP.MianPanel();//主面板对象

//FileModel命名空间
WEBKP.namespace('FileModel');
WEBKP.FileModel = function(){
    this._obj = '';
    this.domId = "";
    this.fileId = "";
    this.fileName = "";
    this.ModifyTime = "";
    this.parentId = "";
    this.fileType = "";
    this.isImage = "";
    this.isCanConvert = "";
    this.isCanWow = "";
}
WEBKP.FileModel.prototype = {
    _loadData: function($tr){
        this._obj = $tr;
        this.fileId = $tr.attr('fileid');
        this.fileName = $tr.attr('fileName');
        this.fileType = $tr.attr('filetype');
        this.isImage = $tr.attr('isImage');
        this.isCanConvert = $tr.attr('isCanConvert');
        this.isCanWow = $tr.attr('isCanWow');
        this.fileVer = $tr.attr('fileVer');
        this.isdel = $tr.attr('isdel');
        this.shareId = $tr.attr('shareId');
        var $checkObj = $tr.find('input');
        MainPanelObj.updateSelectFile(this.fileType, this.fileId, $checkObj.attr('checked'));//进入
    },
    _filterData: function(opts){
        var $checkObj = this._obj.find('input');
        var type = opts.type;
        if (type) {
            $checkObj.attr('checked', true);
            MainPanelObj.updateSelectFile(this.fileType, this.fileId, true);
        }
        else {
            $checkObj.attr('checked', false);
            MainPanelObj.updateSelectFile(this.fileType, this.fileId, false);
        }
    },
    init: function(tr){
        this._loadData($(tr));
    },
    ExecUpdate: function(opts){
        this._filterData(opts);
    }
}
var MainWindow = window;
var ContentWindow = window;


//加载文件列表回调
function loadFileCallBack(MainObj){
    MainPanelObj.scroolTop();
    MainPanelObj.checkAllSubject = ContentWindow.document.getElementById('filtercheck');
    if (MainPanelObj.checkAllSubject) {
        inherits(new Subject(), MainPanelObj.checkAllSubject);
        $(MainPanelObj.checkAllSubject).unbind('click').click(function(e){//全选
            if(this.checked){
                $("#filelistwrap").find('tr').addClass('ui-selected').attr('chked','1');
            }else{
                $("#filelistwrap").find('tr').removeClass('ui-selected').attr('chked','0');
            }
            MainPanelObj.checkAllSubject.Notify({
                type: this.checked
            });
            CreateMenu();//创建菜单
        })
        var trListObj = $(MainObj).find('tr');
        var fileObj;
        for (var i = 0, trLen = trListObj.length; i < trLen; i++) {
            var trObj = trListObj[i];
            fileObj = new WEBKP.FileModel();
            fileObj.init(trObj);
            inherits(new Observer(), fileObj);
            fileObj.Update = function(value){
                this.ExecUpdate(value);
            }
            MainPanelObj.checkAllSubject.AddObserver(fileObj);
        }
    }
    
    $(MainObj).find('tr[filetype="file"] a').unbind('click').click(function(e)
    {
        if($(this).parent('del').length==1)
        {
             e.stopPropagation();
            return false;
        }else{
             e.stopPropagation();
             var defaultOP = $(this).attr('defaultop');
             CommandCenter.handler(defaultOP, $(this).attr('fileid'));
             return false;
        }
    })
    $(MainObj).find('tr').unbind('mouseenter').mouseenter(function(){
        var obj = $(this);
        var chked = obj.attr('chked');
        if(!(chked&&'1'==chked)){
            $(this).addClass('showaction');
        }
    }).unbind('mouseleave').mouseleave(function(){
        var obj = $(this);
        var chked = obj.attr('chked');
        if(!(chked&&'1'==chked)){
            obj.removeClass('showaction');
        }
    })
    
    $(MainObj).find('.list-chk').unbind('click').click(function(e)
    {
        var trObj = $(this).parent('tr');
        trObj.toggleClass("ui-selected");
        var chkObj = $(this).find("input");
        if(trObj.hasClass("ui-selected"))
        {
            //清除以前的选择，进行单选
            MainPanelObj.clearSelectFilesId();
            $("#filelistwrap").find('input:checked').attr('checked',false);
            $("#filelistwrap").find(".ui-selected").removeClass('ui-selected');
        
            chkObj.attr('checked',true);
            MainPanelObj.updateSelectFile(trObj.attr('filetype'), trObj.attr('fileid'), true);
        }else
        {
            chkObj.attr('checked',false);
            MainPanelObj.updateSelectFile(trObj.attr('filetype'), trObj.attr('fileid'), false);
        }
        e.stopPropagation();
        CreateMenu();//创建菜单
    })
    CreateMenu();//创建菜单
    // MainPanelObj.clearSelectFilesId();//清空选中的
    //MsgBar.closeMsg();//关掉msgbar
}


var MenuComponent = new Interface("MenuComponent", [["getElement"]]);

WEBKP.namespace('Menu');
WEBKP.Menu = function(text, title, type, href, command, classname, id){
    this.menuComponents = new Array();
    this.text = text;
    this.title = title;
    this.href = href;
    this.classname = '';
    if (command) {
        this.command = command;
    }
    this.type = type;
    if (classname) {
        this.classname = classname;
    }
    if (id) {
        this.id = id;
    }
    Interface.registerImplements(this, MenuComponent);
}

WEBKP.Menu.prototype = {
    getElement: function(){
        if (this.menuComponents.length == 0) {
            //throw new Error(this.text + "菜单下没有子菜单");
        }
        var liElement = MainWindow.document.createElement("li");
        //liElement.className = "bodersild relativeinline buutonleft";
        //divElement.title = this.title;
        //if (this.classname) {
        //   liElement.className = this.classname;
        //}
        switch (this.type) {
            case 'checkbox':
                var checkboxDom = MainWindow.document.createElement('input');
                checkboxDom.type = 'checkbox';
                checkboxDom.id = 'filtercheck';
                liElement.appendChild(checkboxDom);
                break;
        }
        var anchor = MainWindow.document.createElement("a");
        //anchor.className = "Menu-Link";
        anchor.href = this.href;
        if (this.id) {
            anchor.id = this.id;
        }
        anchor.innerHTML =  this.text;
        anchor.className=this.classname;
        liElement.appendChild(anchor);
        var len = this.menuComponents.length;
        if (len > 0) {
            var ulElement = MainWindow.document.createElement("ul");
            liElement.appendChild(ulElement);
            for (var i = 0, len = this.menuComponents.length; i < len; i++) {
                ulElement.appendChild(this.menuComponents[i].getElement());
            }
        }
        var command = this.command;
        if (command) {
            $(anchor).click(function(){
                CommandCenter.execBefore();
                command.execute();
            });
        }
        return liElement;
    },
    add: function(component){
        this.menuComponents.push(component);
    },
    remove: function(component){
        for (var i = 0, len = this.menuComponents.length; i < len; i++) {
            if (this.menuComponents[i] == component) {
                this.menuComponents.splice(i, 1);
                break;
            }
        }
    },
    removeAt: function(index){
        if (this.menuComponents.length <= index) {
            this.menuComponents.splice(index, 1);
        }
        else {
            throw new Error("索引操作数组超过上限");
        }
    }
}

WEBKP.namespace('MenuItem');
WEBKP.MenuItem = function(text, title, type, href, command, classname){
    this.text = text;
    this.title = title;
    this.href = href;
    this.command = command;
    this.classname = classname;
    Interface.registerImplements(this, MenuComponent);
}

WEBKP.MenuItem.prototype = {
    getElement: function(){
        var liElement = MainWindow.document.createElement("li");
        //liElement.className = "Menu-Leaf";
        //liElement.title = this.title;
        var anchor = MainWindow.document.createElement("a");
        anchor.href = this.href;
        anchor.innerHTML = this.text;
        anchor.className=this.classname;
        liElement.appendChild(anchor);
        var command = this.command;
        if (command) {
            $(anchor).click(function(){
                CommandCenter.execBefore();
                command.execute();
            })
        }
        // addEvent(anchor, "click", function(){
        //    command.execute();
        //});
        return liElement;
    }
}



var ICommand = new Interface("ICommand", [["execute"]]);
//新建文件夹命令
WEBKP.namespace('onCreateCommand');
WEBKP.onCreateCommand = function(){
    Interface.registerImplements(this, ICommand);
}
WEBKP.onCreateCommand.prototype.execute = function(){
    var folderList = MainPanelObj.getAllFiles('folder');//取所有的文件夹
    var existNumFlag = [];
    for (var i = 0, len = folderList.length; i < len; i++) {
        var fileName = folderList[i].fileName;
        if (fileName.indexOf('新建文件夹') != -1) {
            var fileNameNum = fileName.replace(/新建文件夹/ig, '');
            fileNameNum = fileNameNum.replace(/\(/ig, '');
            fileNameNum = fileNameNum.replace(/\)/ig, '');
            fileNameNum = parseInt(fileNameNum);
            if (isNaN(fileNameNum)) {
                fileNameNum = 0;
            }
            existNumFlag.push(fileNameNum);//存储已经存在的文件夹编号
        }
    }
    var getFileNum = '';
    var flen = existNumFlag.length;
    for (var k = 0; k < flen; k++) {
        if ($.inArray(k, existNumFlag) == -1) {
            getFileNum = k;
            break;
        }
    }
    var newFileName = '';
    switch (getFileNum) {
        case '':
            if (flen == 0) {
                newFileName = '新建文件夹';
            }
            else {
                newFileName = '新建文件夹 (' + flen + ')';
            }
            break;
        case 0:
            newFileName = '新建文件夹';
            break;
        default:
            newFileName = '新建文件夹 (' + getFileNum + ')';
    }
    NewDirHandler.doHandler(newFileName);
};

//共享文件命名
WEBKP.namespace('onShareCommand');
WEBKP.onShareCommand = function(fileId){
    Interface.registerImplements(this, ICommand);
    this.fileId = fileId || 'NO';
}
WEBKP.onShareCommand.prototype.execute = function(){
    var selectFile = MainPanelObj.getSelectFile();
    var totalNum = selectFile[2];//选择的总文件(夹）数
    if (this.fileId == 'NO') {
        if (typeof totalNum != 'undefined' && totalNum == 0) {
            MsgBar.showMsg('您沒有选择任何文件（夹）');
        }
        else {
            var allFiles = MainPanelObj.getSelectFilesId();
            var len = allFiles.length;
            if (len == 1) {
                var fileObj = MainPanelObj.getFileInfoByFileId(allFiles[0]);
                var url = "http://" + window.location.host + "/" + userId + "/" + dirId + "/download_file/" + fileObj.fileName;
                popRef.confirmInfo({
                    icoCls: '',
                    msgCls: 'confirm',
                    message: '<div class="pop-frm" >文件 '+ fileObj.fileName +' 共享链接：<textarea cols="30" rows="3">' + url + '</textarea></div>',
                    title: '共享文件',
                    height: 200,
                    handler: function(e){
                        popRef.close();
                    },
                    autoClose: false
                });
                /*
                if(!isEmail(userEmail))
                {
                    //bindEmailObj.bindNotice();
                    //if(typeof mergeflag !='undefined'&&'1'==mergeflag){
                    //    bindEmailObj.bindNotice();
                    //}else{
                        popRef.win({'title':'请注册一个有效邮箱来开启共享功能',width:380,height:280,message:'',iframe:{'id':'sdfasfasd','name':'zxcvz12','src':'index.php?ac=fileview_handler&op=bindthirdview'}})
                    //}
                }else
                {
                    //MsgBar.showMsg();
                    var fileObj = MainPanelObj.getFileInfoByFileId(allFiles[0]);
                    var title = '设置共享';
                    popRef.win({
                        title: title + ' — ' + fileObj.fileName,
                        fixPosition: true,
                        width: 680,
                        height: 490,
                        message:'',
                        iframe:{id:'sdfsf',name:'dfsafsadf',src:'index.php?ac=fileview_handler&op=shareview&fileid=' + allFiles[0]},
                        btn: [['取消所有共享', 'cancelallshare'], ['确定共享', 'okshare'],['关闭','cancelwin']],
                        handler: function(e){
                            switch (e) {
                                case 'close':
                                case 'cancelwin':
                                    popRef.close();
                                    break;
                                default:
                                    popRef.getPage().contentWindow.handlerOperate(e);
                            }
                        },
                        autoClose: false
                    })
                }
                */
            }
            else {
                MsgBar.showMsg('您选择了' + len + '个文件（夹），目前暂不支持批量共享操作');
            }
        }
    }
    else {
        //MsgBar.showMsg();
        popRef.win({
            title: '共享文件（夹）',
            fixPosition: true,
            width: 450,
            height: 300,
            message:'index.php?ac=fileview_handler&op=shareview&fileid=' + this.fileId,
            iframe:true
        })
    }
};

//取消共享
WEBKP.namespace('onCancelShareCommand');
WEBKP.onCancelShareCommand = function(fileId){
    Interface.registerImplements(this, ICommand);
    this.fileId = fileId || 'NO';
}
WEBKP.onCancelShareCommand.prototype.execute = function(){
    var selectFile = MainPanelObj.getSelectFile();
    var totalNum = selectFile[2];//选择的总文件(夹）数
    if (this.fileId == 'NO') {
        if (typeof totalNum != 'undefined' && totalNum == 0) {
            MsgBar.showMsg('您沒有选择任何文件（夹）');
        }
        else {
            var allFiles = MainPanelObj.getSelectFilesId();
            var len = allFiles.length;
            if (len == 1) {
                MsgBar.showMsg();
                var fileObj = MainPanelObj.getFileInfoByFileId(allFiles[0]);
                var message = (fileObj.fileType == 'folder') ? '文件夹' : '文件';
                popRef.confirmInfo({
                    title: '取消共享',
                    width:400,
                    height:200,
                    message: ['是否取消', message, ':"', CommFormatFileName(fileObj.fileName,25,3), '" 的共享'].join(''),
                    autoClose:false,
                    handler: function(e){
                        switch(e)
                        {
                            case 'ok':
                                $.ajax({
                                    url:"index.php?ac=fileview_handler&op=cancelshare",
                                    dataType:'json',
                                    type:'post',
                                    data:{'fileId':allFiles[0]},
                                    success:function(res)
                                    {
                                        if(res&&'ok' == res.xLive_attr.result)
                                        {
                                            popRef.close();
                                            popRef.succeedInfo({'title':'取消共享','message':'取消共享成功',handler:function(e){
                                                MainPanelObj.refreshFilePanel('share',{'fileId':allFiles[0]});//刷新面板
                                            }});
                                        }else
                                        {
                                            popRef.close();
                                            popRef.errorInfo({'title':'取消共享','message':'取消共享失败'});
                                        }
                                    }
                                })
                                break;
                            case 'close':
                            case 'cancel':
                                popRef.close();
                                break;
                        }
                    }
                })
            }
            else {
                MsgBar.showMsg('您选择了' + len + '个文件（夹），目前暂不支持批量取消共享操作');
            }
        }
    }
    else {
        MsgBar.showMsg();
        var fileObj = MainPanelObj.getFileInfoByFileId(this.fileId);
        var message = (fileObj.fileType == 'folder') ? '文件夹' : '文件';
        popRef.confirmInfo({
            title: '取消共享',
            message: ['是否取消', message, ':', fileObj.fileName, '的共享'].join(''),
            handler: function(e){
                switch(e)
                {
                    case 'ok':
                        $.ajax({
                            url:"index.php?ac=fileview_handler&op=cancelshare",
                            dataType:'json',
                            type:'post',
                            data:{'fileId':fileObj.fileId},
                            success:function(res)
                            {
                                
                            }
                        })
                        break;
                    case 'close':
                    case 'cancel':
                        popRef.close();
                        break;
                }
            }
        })
    }
};

//退出共享
WEBKP.namespace('onExitShareCommand');
WEBKP.onExitShareCommand = function(fileId){
    Interface.registerImplements(this, ICommand);
    this.fileId = fileId || 'NO';
}
WEBKP.onExitShareCommand.prototype.execute = function(){
    var selectFile = MainPanelObj.getSelectFile();
    var totalNum = selectFile[2];//选择的总文件(夹）数
    if (this.fileId == 'NO') {
        if (typeof totalNum != 'undefined' && totalNum == 0) {
            MsgBar.showMsg('您沒有选择任何文件（夹）');
        }
        else {
            var allFiles = MainPanelObj.getSelectFilesId();
            var len = allFiles.length;
            if (len == 1) {
                MsgBar.showMsg();
                var fileObj = MainPanelObj.getFileInfoByFileId(allFiles[0]);
                var message = (fileObj.fileType == 'folder') ? '文件夹' : '文件';
                popRef.confirmInfo({
                    'title': '退出共享',
                    width:400,
                    height:200,
                    message: ['是否退出', message, ':"', CommFormatFileName(fileObj.fileName,25,3), '" 的共享'].join(''),
                    autoClose:false,
                    handler: function(e){
                        switch(e)
                        {
                            case 'ok':
                                $.ajax({
                                    url:"index.php?ac=fileview_handler&op=exitshare",
                                    dataType:'json',
                                    type:'post',
                                    data:{'fileId':allFiles[0]},
                                    success:function(res)
                                    {
                                        if(res&&'ok' == res.result)
                                        {
                                            popRef.close();
                                            popRef.succeedInfo({'title':'退出共享','message':'退出共享成功',handler:function(e){
                                                 MainPanelObj.refreshFilePanel();
                                            }});
                                        }else
                                        {
                                            popRef.close();
                                            popRef.errorInfo({'title':'退出共享','message':'退出共享失败'});
                                        }
                                    }
                                })
                                break;
                            case 'close':
                            case 'cancel':
                                popRef.close();
                                break;
                        }
                    }
                })
            }
            else {
                MsgBar.showMsg('您选择了' + len + '个文件（夹），目前暂不支持批量退出共享操作');
            }
        }
    }
    else {
        MsgBar.showMsg();
        var fileObj = MainPanelObj.getFileInfoByFileId(this.fileId);
        var message = (fileObj.fileType == 'folder') ? '文件夹' : '文件';
        popRef.confirmInfo({
            title: '退出共享',
            message: ['是否退出', message, ':', fileObj.fileName, '的共享'].join(''),
            handler: function(e){
                switch(e)
                {
                    case 'ok':
                        $.ajax({
                            url:"index.php?ac=fileview_handler&op=exitshare",
                            dataType:'json',
                            type:'post',
                            data:{'fileId':fileObj.fileId},
                            success:function(res)
                            {
                                
                            }
                        })
                        break;
                    case 'close':
                    case 'cancel':
                        popRef.close();
                        break;
                }
            }
        })
    }
};

//上传文件命令
WEBKP.namespace('onUploadCommand');
WEBKP.onUploadCommand = function(){
    Interface.registerImplements(this, ICommand);
}
WEBKP.onUploadCommand.prototype.execute = function(){
    popRef.win({
        title: '上传文件',
        width: 600,
        height: 400,
        maxBtn: false,
        message:'',
        iframe:{'id':'uploadifram2e' , 'name':'uploadiframe1', 'src':'/upload.php'},
        autoClose:false,
        showMask:false,
       // btn: [['取消上传', 'canceluplaod'], ['隐藏窗口', 'cancel']],
        handler:function(e){
            switch(e){
                case 'close':
                    try{
                        var r = popRef.getPage().contentWindow.cancelUpload();
                        if(r){
                            popRef.close();
                        }
                    }catch(e){
                        popRef.close();
                    }
                    break;
                case 'cancel':
                    //popRef.min();
                    //$("#ym-window").css('visibility','hidden');
                    break;
                case 'canceluplaod':
                    try{
                        var r = popRef.getPage().contentWindow.cancelUpload();
                    }catch(e){
                    }
                    break;
            }
        }
    });
    //上传隐藏窗口
    /*
    $(".ym-header-tools").click(function(e){
        var html = $(e.target).html();
        if('<strong>2</strong>'==html||'<strong>0</strong>'==html)//最小化
        {
            $("#ym-window").css('height','0px');
            $("#showuploadpress").show();
        }
    });
    $("#showuploadpress").click(function(){
        $("#ym-window").css('height','400px').find('.ymPrompt_normal').addClass('ymPrompt_min').removeClass('ymPrompt_normal');
        $("#showuploadpress").hide();
    })
    */
};

//删除命令
WEBKP.namespace('onDeleteCommand');
WEBKP.onDeleteCommand = function(){
    Interface.registerImplements(this, ICommand);
}
WEBKP.onDeleteCommand.prototype.execute = function(){
    var selectFile = MainPanelObj.getSelectFile();
    var totalNum = selectFile[2];//选择的总文件(夹）数
    if (typeof totalNum != 'undefined' && totalNum == 0) {
        MsgBar.showMsg('您沒有选择任何文件（夹）');
    }
    else {
        var allFiles = MainPanelObj.getSelectFilesId();
        var fileObj = MainPanelObj.getFileInfoByFileId(allFiles[0]);
        
        popRef.confirmInfo({
            title: '确认删除',
            message: '您确定要删除这' + allFiles.length + '项吗?',
            handler: function(e){
                switch (e) {
                    case 'ok':
                        $.ajax({
                            url: 'delete.php',
                            dataType: 'json',
                            data: {
                                'ownerid':  userId,
                                'parentid': dirId,
                                'type': fileObj.fileType,
                                'name': fileObj.fileName
                            },
                            type: 'post',
                            beforeSend:function()
                            {
                                popRef.win({
                                    title: '正在删除',
                                    icoCls:'ymPrompt_loader',
                                    message: '<div>删除文件(夹）操作处理中……</div>'
                                });
                            },
                            success: function(res){
                                popRef.close();
                                if (res) {
                                    var succsum = 0, errsum = 0, len = res.length;
                                    var okFileList =[];
                                    for (var i = 0; i < len; i++) {
                                        if ('ok' == res[i].result) {
                                            //$("#tr" + res[i].fileId).remove();
                                            succsum++;
                                            okFileList.push(res[i].fileId);
                                        }
                                        else {
                                            errsum++;
                                        }
                                    }
                                    if (succsum == len) {
                                        popRef.succeedInfo({
                                            title: '操作结果',
                                            message: ['操作成功，成功删除', succsum, '项'].join('')
                                        });
                                        MainPanelObj.refreshFilePanel();
                                        //MainPanelObj.refreshFilePanel('delete', okFileList);
                                    }
                                    else {
                                        popRef.alert({
                                            title: '操作结果',
                                            message: ['成功删除', succsum, '项,失败', errsum, '项'].join('')
                                        });
                                        MainPanelObj.refreshFilePanel();
                                        //MainPanelObj.refreshFilePanel('delete', okFileList);
                                    }
                                }
                            }
                        })
                        break;
                    case 'cancel':
                    case 'close':
                        popRef.close();
                        break;
                }
            }
        })
    }
};

//下载命令
WEBKP.namespace('onDownCommand');
WEBKP.onDownCommand = function(fileId){
    Interface.registerImplements(this, ICommand);
    this.fileId = fileId || 'NO';
}
WEBKP.onDownCommand.prototype.execute = function(){
    var selectFile = MainPanelObj.getSelectFile();
    var totalNum = selectFile[2];//选择的总文件(夹）数
    if (this.fileId == 'NO') {
        if (typeof totalNum != 'undefined' && totalNum == 0) {
            MsgBar.showMsg('您沒有选择任何文件（夹）');
        }
        else {
            var allFiles = MainPanelObj.getSelectFilesId();
            var len = allFiles.length;
            if (len == 1) {
                MsgBar.showMsg();
                this.downloadHandler(allFiles[0]);
            }
            else {
                MsgBar.showMsg('您选择了' + len + '个文件（夹），目前暂不支持批量下载操作');
            }
        }
    }
    else {
        this.downloadHandler(this.fileId);
    }
}
WEBKP.onDownCommand.prototype.downloadHandler = function(fileId){
    var fileObj = MainPanelObj.getFileInfoByFileId(fileId);
    var fileName = fileObj.fileName;
    var fileId = fileObj.fileId;
    var fileType = fileObj.fileType;
    
    if('file'==fileType)
    {
        if(typeof newuploaddown_enable=='undefined'||!newuploaddown_enable)//old下载方式
        {
            alert("abc");
            if ($.browser.msie) {
                fileName = encodeURIComponent(fileName);
            }
            else {
                fileName = encodeURIComponent(fileName.replace(/\s/g, '_'));
            }
            window.setTimeout(function(){
                $.getJSON("index.php?ac=fileview_handler&op=getdownurl&fileId=" + fileId + "&callback=?", function(resData){
                    $("#dfileId").val(fileId);
                    $("#detoken").val(resData.etoken);
                    $("#downloadform").attr('action', (resData.url + '/download/' + fileName));
                    $("#downloadform").submit();
                });
            },0);
        }else
        {
            //will go to here
            window.open('/'+userId+'/'+dirId+'/download_file/'+fileName,'openwindow');
        }
    }else
    {
        MsgBar.showMsg('目前暂不支持目录下载操作');
        //window.open(pubstor_server+'/cdlsched/getdl?fid='+fileId+'&token='+userToken);
    }
}


//编辑命令
WEBKP.namespace('onEditCommand');
WEBKP.onEditCommand = function(fileId){
    Interface.registerImplements(this, ICommand);
    this.fileId = fileId || 'NO';
}
WEBKP.onEditCommand.prototype.execute = function(){
    var selectFile = MainPanelObj.getSelectFile();
    var totalNum = selectFile[2];//选择的总文件(夹）数
    if (this.fileId == 'NO') {
        if (typeof totalNum != 'undefined' && totalNum == 0) {
            MsgBar.showMsg('您沒有选择任何文件（夹）');
        }
        else {
            var allFiles = MainPanelObj.getSelectFilesId();
            var len = allFiles.length;
            if (len == 1) {
                //MsgBar.showMsg();
                window.open(createEditUrl(allFiles[0]));
            }
            else {
                MsgBar.showMsg('您选择了' + len + '个文件（夹），目前暂不支持批量编辑操作');
            }
        }
    }
    else {
        window.open(createEditUrl(this.fileId));
    }
}

//查看命令
WEBKP.namespace('onBrowseCommand');
WEBKP.onBrowseCommand = function(fileId){
    Interface.registerImplements(this, ICommand);
    this.fileId = fileId || 'NO';
}
WEBKP.onBrowseCommand.prototype.execute = function(){
    var selectFile = MainPanelObj.getSelectFile();
    var totalNum = selectFile[2];//选择的总文件(夹）数
    if (this.fileId == 'NO') {
        if (typeof totalNum != 'undefined' && totalNum == 0) {
            MsgBar.showMsg('您沒有选择任何文件（夹）');
        }
        else {
            var allFiles = MainPanelObj.getSelectFilesId();
            var len = allFiles.length;
            if (len == 1) {
                var fileObj = MainPanelObj.getFileInfoByFileId(allFiles[0]);
                window.open(createBrowseUrl(fileObj, true));
            }
            else {
                MsgBar.showMsg('您选择了' + len + '个文件（夹），目前暂不支持批量查看操作');
            }
        }
    }
    else {
        var fileObj = MainPanelObj.getFileInfoByFileId(this.fileId);
        if('1' == fileObj.isImage)
        {
            $("#lll"+fileObj.fileId).click();
        }else{
            window.open(createBrowseUrl(fileObj, true));
        }
    }
}

//移动命令
WEBKP.namespace('onMoveCommand');
WEBKP.onMoveCommand = function(){
    Interface.registerImplements(this, ICommand);
}
WEBKP.onMoveCommand.prototype.execute = function(){
    var selectFile = MainPanelObj.getSelectFile();
    var totalNum = selectFile[2];//选择的总文件(夹）数
    if (typeof totalNum != 'undefined' && totalNum == 0) {
        MsgBar.showMsg('您沒有选择任何文件（夹）');
    }
    else {
        var allFiles = MainPanelObj.getSelectFilesId();
        var len = allFiles.length;
        var fileLisInfo = [];
        while (len--) {
            var fileObj = MainPanelObj.getFileInfoByFileId(allFiles[len]);
            fileLisInfo.push(fileObj);
        }
        MoveRecover.showPanel(fileLisInfo, 'move');
    }
}

//历史记录
WEBKP.namespace('onHistoryCommand');
WEBKP.onHistoryCommand = function(){
    Interface.registerImplements(this, ICommand);
}
WEBKP.onHistoryCommand.prototype.execute = function(){
    var selectFile = MainPanelObj.getSelectFile();
    var totalNum = selectFile[2];//选择的总文件(夹）数
    if (typeof totalNum != 'undefined' && totalNum == 0) {
        MsgBar.showMsg('您沒有选择任何文件（夹）');
    }
    else {
        var allFiles = MainPanelObj.getSelectFilesId();
        var fileObj = MainPanelObj.getFileInfoByFileId(allFiles[0]);
        popRef.win({
            title: '文件历史记录',
            fixPosition: true,
            width: 650,
            height: 450,
            iframe:true,
            message:'index.php?ac=fileview_handler&op=historyview&fileid=' + fileObj.fileId + '&filever=' + fileObj.fileVer
        })
    }
}

//还原命令
WEBKP.namespace('onRecoverCommand');
WEBKP.onRecoverCommand = function(fileId){
    Interface.registerImplements(this, ICommand);
    this.fileId = fileId || 'NO';
}
WEBKP.onRecoverCommand.prototype.execute = function(){
    var selectFile = MainPanelObj.getSelectFile();
    var totalNum = selectFile[2];//选择的总文件(夹）数
    if (this.fileId == 'NO') {
        if (typeof totalNum != 'undefined' && totalNum == 0) {
            MsgBar.showMsg('您沒有选择任何文件（夹）');
        }
        else {
            var allFiles = MainPanelObj.getSelectFilesId();
            var len = allFiles.length;
            var url = 'index.php?ac=fileview_handler&op=recover';
            var postData  = {fileId:allFiles};
            if(selectFile[1]>0)//有文件夹
            {
                url = 'index.php?ac=fileview_handler&op=recoverfiles';
                postData = {fileId:MainPanelObj.selectFileIds,'folderId':MainPanelObj.selectFolderIds};
            }
            //var fileLisInfo = [];
            //for(var i =0;i<len;i++)
            //{
                //var fileObj = MainPanelObj.getFileInfoByFileId();
                //fileLisInfo.push(allFiles[i]);
            //}
            //MoveRecover.showPanel(fileLisInfo, 'recover');
            var fileObj = MainPanelObj.getFileInfoByFileId(allFiles[0]);
            popRef.confirmInfo({
                'title':'还原文件',
                message: '您确定要还原这' + len + '个文件（夹）吗？',
                handler: function(e){
                    switch (e) {
                        case 'ok':
                            popRef.close();
                            popRef.win({
                                'title':'还原操作中',
                                icoCls:'ymPrompt_loader',
                                'message':'正在还原操作，请稍候……',
                                btn:[['关闭','gb']]})
                            $.ajax({
                                url:'recover.php',
                                type:'post',
                                dataType:'json',
                                data: {
                                'ownerid':  userId,
                                'parentid': dirId,
                                'type': fileObj.fileType,
                                'name': fileObj.fileName
                                },
                                success:function(res)
                                {
                                    if(res)
                                    {
                                        var ssum =0;
                                        var esum = 0;
                                        var okFileList = [];
                                        for(var i=0,n = res.length;i<n;i++)
                                        {
                                            if('ok' == res[i].result)
                                            {
                                                ssum++;
                                                okFileList.push(res[i].fileId);
                                                   //$("#tr" + res[i].fileId).remove();
                                                
                                            }else
                                            {
                                                esum++;
                                            }
                                        }
                                        popRef.close();
                                        if(0==esum){
                                            popRef.succeedInfo({'title':'还原成功',message:'还原操作成功，共还原'+ssum+'项',handler:function(){MainPanelObj.refreshFilePanel('recove', okFileList);}});
                                        }
                                        else{
                                            popRef.alert({'title':'还原结果',message:'成功还原'+ssum+'项，失败'+esum+'项',handler:function(){MainPanelObj.refreshFilePanel('recove', okFileList);}});
                                        }
                                    }
                                },
                                error:function(xhr,msg)
                                {
                                    popRef.close();
                                    popRef.alert({'title':'还原失败',message:'还原失败，请稍候再试'});
                                }
                            })
                            break;
                        case 'cancel':
                        case 'close':
                            break;
                    }
                }
            })
        }
    }
    else {
        var fileObj = MainPanelObj.getFileInfoByFileId(this.fileId);
        MoveRecover.showPanel([fileObj], 'recover');
    }
}

//重命名文件
WEBKP.namespace('onReNameCommand');
WEBKP.onReNameCommand = function(fileId){
    Interface.registerImplements(this, ICommand);
    this.fileId = fileId || 'NO';
}
WEBKP.onReNameCommand.prototype.execute = function(){
    var selectFile = MainPanelObj.getSelectFile();
    var totalNum = selectFile[2];//选择的总文件(夹）数
    if (this.fileId == 'NO') {
        if (typeof totalNum != 'undefined' && totalNum == 0) {
            MsgBar.showMsg('您沒有选择任何文件（夹）');
        }
        else {
            var allFiles = MainPanelObj.getSelectFilesId();
            var len = allFiles.length;
            if (len == 1) {
                var fileObj = MainPanelObj.getFileInfoByFileId(allFiles[0]);
                ReNameHandler.doHandler(fileObj);
            }
            else {
                MsgBar.showMsg('您选择了' + len + '个文件（夹），目前暂不支持批量重命名操作');
            }
        }
    }
    else {
        ReNameHandler.doHandler(this.fileId);
    }
};


//还原命令
WEBKP.namespace('onCleanRecycleCommand');
WEBKP.onCleanRecycleCommand = function(fileId){
    Interface.registerImplements(this, ICommand);
    this.fileId = fileId || 'NO';
}
WEBKP.onCleanRecycleCommand.prototype.execute = function(){
    var selectFile = MainPanelObj.getSelectFile();
    var totalNum = selectFile[2];//选择的总文件(夹）数
    if (this.fileId == 'NO') {
        if (typeof totalNum != 'undefined' && totalNum == 0) {
            MsgBar.showMsg('您沒有选择任何文件（夹）');
        }
        else {
            var allFiles = MainPanelObj.getSelectFilesId();
            var len = allFiles.length;
            var url = 'index.php?ac=fileview_handler&op=cleanrecycle';
            var postData  = {fileId:allFiles};
            if(selectFile[1]>0)//有文件夹
            {
                url = 'index.php?ac=fileview_handler&op=cleans';
                postData = {fileId:MainPanelObj.selectFileIds,'folderId':MainPanelObj.selectFolderIds};
            }
            popRef.confirmInfo({
                'title':'删除文件（夹）',
                message: '您确定要删除这' + len + '个文件（夹）吗？删除后将不能找回。',
                handler: function(e){
                    switch (e) {
                        case 'ok':
                            popRef.close();
                            popRef.win({
                                'title':'删除操作中',
                                icoCls:'ymPrompt_loader',
                                'message':'正在删除操作，请稍候……',
                                btn:[['关闭','gb']]})
                            $.ajax({
                                url:url,
                                type:'post',
                                dataType:'json',
                                data:postData,
                                success:function(res)
                                {
                                    if(res)
                                    {
                                        var ssum =0;
                                        var esum = 0;
                                        var okFileList = [];
                                        for(var i=0,n = res.length;i<n;i++)
                                        {
                                            if('ok' == res[i].result)
                                            {
                                                ssum++;
                                                okFileList.push(res[i].fileId);
                                                   //$("#tr" + res[i].fileId).remove();    
                                            }else
                                            {
                                                esum++;
                                            }
                                        }
                                        popRef.close();
                                        if(0==esum){
                                            popRef.succeedInfo({'title':'删除成功',message:'删除操作成功，共删除'+ssum+'项',handler:function(){MainPanelObj.refreshFilePanel('realdel', okFileList);}});
                                        }
                                        else{
                                            popRef.alert({'title':'删除结果',message:'成功删除'+ssum+'项，失败'+esum+'项',handler:function(){MainPanelObj.refreshFilePanel('realdel', okFileList);}});
                                        }
                                    }
                                },
                                error:function(xhr,msg)
                                {
                                    popRef.close();
                                    popRef.alert({'title':'删除失败',message:'删除失败，请稍候再试'});
                                }
                            })
                            break;
                        case 'cancel':
                        case 'close':
                            break;
                    }
                }
            })
        }
    }
    else {
        var fileObj = MainPanelObj.getFileInfoByFileId(this.fileId);
        MoveRecover.showPanel([fileObj], 'realdel');
    }
}



WEBKP.namespace('onCleanAllRecycleCommand');
WEBKP.onCleanAllRecycleCommand = function(){
    Interface.registerImplements(this, ICommand);
}
WEBKP.onCleanAllRecycleCommand.prototype.execute = function(){
    popRef.confirmInfo({
        'title': '清空回收站',
        message: '您确定要清空回收站吗？',
        handler: function(e){
            switch (e) {
                case 'ok':
                    $.ajax({
                        url: 'index.php?ac=fileview_handler&op=cleanallrecycle',
                        type: 'post',
                        dataType: 'json',
                        data: {
                            fileId: '-1'
                        },
                        success: function(res){
                            popRef.close();
                            if(res&&'ok' == res.result)
                            {
                                popRef.succeedInfo({'title':'操作成功','message':'清空回收站成功',handler:function(e){
                                    location.href = [Site_Url,'index.php?ac=fileview&op=recycle'].join('');
                                }});
                            }else
                            {
                                popRef.succeedInfo({'title':'操作失败','message':'清空回收站失败'});
                            }
                        }
                    })
                    break;
                case 'close':
                case 'cancel':
                    popRef.close();
                    break;
            }
        }
    })
}

//删除回收站中的文件
WEBKP.namespace('onCleanRecycleCommand1');
WEBKP.onCleanRecycleCommand1 = function(){
    Interface.registerImplements(this, ICommand);
}
WEBKP.onCleanRecycleCommand1.prototype.execute = function(){
    var selectFile = MainPanelObj.getSelectFile();
    var totalNum = selectFile[2];//选择的总文件(夹）数
    if (typeof totalNum != 'undefined' && totalNum == 0) {
        MsgBar.showMsg('您沒有选择任何文件（夹）');
    }
    else {
        var allFiles = MainPanelObj.getSelectFilesId();
        var len = allFiles.length;
        popRef.confirmInfo({'title':'删除文件','message':'您确实要删除这' + len + '项吗？删除后将无法找回。',handler:function(e){
            switch(e)
            {
                case 'ok':
                    popRef.close();
                    popRef.win({
                        'title':'删除操作中',
                        icoCls:'ymPrompt_loader',
                        'message':'正在删除操作，请稍候……',
                        btn:[['关闭','gb']]})
                    $.ajax({
                        url:'index.php?ac=fileview_handler&op=cleanrecycle',
                        type:'post',
                        dataType:'json',
                        data:{fileId:allFiles},
                        success:function(res)
                        {
                            if(res)
                            {
                                var ssum =0;
                                var esum = 0;
                                var okFileList= [];
                                for(var i=0,n = res.length;i<n;i++)
                                {
                                    if('ok' == res[i].result)
                                    {
                                        ssum++;
                                        okFileList.push(res[i].fileId);
                                           //$("#tr" + res[i].fileId).remove();
                                        
                                    }else
                                    {
                                        esum++;
                                    }
                                }
                                MainPanelObj.refreshFilePanel('delete', okFileList);
                                popRef.close();
                                if(0==esum){
                                    popRef.succeedInfo({'title':'删除成功',message:'删除操作成功，共删除'+ssum+'项'});
                                }
                                else{
                                    popRef.alert({'title':'删除结果',message:'成功删除'+ssum+'项，失败'+esum+'项'});
                                }
                                //MainPanelObj.clearSelectFilesId()
                                //CreateMenu();
                                //MainPanelObj.refreshFilePanel('delete', allFiles);
                            }
                        },
                        error:function(xhr,msg)
                        {
                            popRef.close();
                            popRef.alert({'title':'删除失败',message:'删除失败，请稍候再试'});
                        }
                    })
                    break;
                case 'close':
                case 'cancel':
                    break;
            }
        }})
    }
};


//外链相关的命令
WEBKP.namespace('onPublishOutLinkCommand');
WEBKP.onPublishOutLinkCommand = function(fileId){
    Interface.registerImplements(this, ICommand);
    this.fileId = fileId || 'NO';
}
WEBKP.onPublishOutLinkCommand.prototype.execute = function(){
    var selectFile = MainPanelObj.getSelectFile();
    var totalNum = selectFile[2];//选择的总文件(夹）数
    if (this.fileId == 'NO') {
        if (typeof totalNum != 'undefined' && totalNum == 0) {
            MsgBar.showMsg('您沒有选择任何文件（夹）');
        }
        else {
            var allFiles = MainPanelObj.getSelectFilesId();
            var len = allFiles.length;
            if (len == 1) {
                var fileObj = MainPanelObj.getFileInfoByFileId(allFiles[0]);
                OutLinkHandler.showPanel(fileObj);
            }
            else {
                MsgBar.showMsg('您选择了' + len + '个文件（夹），目前暂不支持批量重命名操作');
            }
        }
    }
    else {
        var fileObj = MainPanelObj.getFileInfoByFileId(this.fileId);
        OutLinkHandler.showPanel(fileObj);
    }
};

//取消外链发布
WEBKP.namespace('onCancelOutlinkCommand');
WEBKP.onCancelOutlinkCommand = function(fileId){
    Interface.registerImplements(this, ICommand);
    this.fileId = fileId || 'NO';
}
WEBKP.onCancelOutlinkCommand.prototype.execute = function(){
    var selectFile = MainPanelObj.getSelectFile();
    var totalNum = selectFile[2];//选择的总文件(夹）数
    if (this.fileId == 'NO') {
        if (typeof totalNum != 'undefined' && totalNum == 0) {
            MsgBar.showMsg('您沒有选择任何文件（夹）');
        }
        else {
            var allFiles = MainPanelObj.getSelectFilesId();
            OutLinkHandler.doCancelOutlinkHandler(allFiles);
        }
    }
    else {
        OutLinkHandler.doCancelOutlinkHandler([this.fileId]);
    }
};
//查看外链
WEBKP.namespace('onBrowseLinkCommand');
WEBKP.onBrowseLinkCommand = function(fileId){
    Interface.registerImplements(this, ICommand);
    this.fileId = fileId || 'NO';
}
WEBKP.onBrowseLinkCommand.prototype.execute = function(){
    var selectFile = MainPanelObj.getSelectFile();
    var totalNum = selectFile[2];//选择的总文件(夹）数
    if (this.fileId == 'NO') {
        if (typeof totalNum != 'undefined' && totalNum == 0) {
            MsgBar.showMsg('您沒有选择任何文件（夹）');
        }
        else {
            var allFiles = MainPanelObj.getSelectFilesId();
            var len = allFiles.length;
            if (len == 1) {
                window.open(createOutLinkUrl(allFiles[0]));
            }
            else {
                // MsgBar.showMsg('您选择了' + len + '个文件（夹），目前暂不支持批量查看操作');
            }
        }
    }
    else {
        window.open(createOutLinkUrl(this.fileId));
    }
};
//复制外链
WEBKP.namespace('onCopyLinkCommand');
WEBKP.onCopyLinkCommand = function(fileId){
    Interface.registerImplements(this, ICommand);
    this.fileId = fileId || 'NO';
}
WEBKP.onCopyLinkCommand.prototype = {
    execute: function(){
        if (this.fileId == 'NO') {
            MsgBar.showMsg('您沒有选择任何文件');
            var selectFile = MainPanelObj.getSelectFile();
            var totalNum = selectFile[2];//选择的总文件(夹）数
            if (typeof totalNum != 'undefined' && totalNum == 0) {
                MsgBar.showMsg('您沒有选择任何文件（夹）');
            }
            else {
                var allFiles = MainPanelObj.getSelectFilesId();
                var len = allFiles.length;
                if (len == 1) {
                    //window.open(createOutLinkUrl(allFiles[0]));
                    var url = createOutLinkUrl(allFiles[0]);
                    var r = copyToClipboard(url);
                    if (r) {
                        $("#copyresult").html('<p>已经成功复制到系统剪贴板</p><p>立即粘贴给qq/msn好友吧！</p>');
                    }
                    else {
                        $("#copyresult").html('<p>您可以把以下外链地址发送给您的qq/msn好友</p>');
                    }
                    this.showCopyWindow(url);
                }
                else {
                    MsgBar.showMsg('您选择了' + len + '个文件（夹），目前暂不支持批量查看操作');
                }
            }
        }
        else {
            var url = createOutLinkUrl(this.fileId);
            var r = copyToClipboard(url);
            if (r) {
                $("#copyresult").html('<p>已经成功复制到系统剪贴板</p><p>立即粘贴给qq/msn好友吧！</p>');
            }
            else {
                $("#copyresult").html('<p>您可以把以下外链地址发送给您的qq/msn好友</p>');
            }
            this.showCopyWindow(url);
        }
    },
    showCopyWindow: function(txt){
        $("#poutlinkurl").html(txt);
        popRef.succeedInfo({
            message: $('#showoutlinkurl').html(),
            title: '复制外链地址',
            allowSelect: true,
            allowRightMenu: true,
            width: 400,
            height: 250
        })
    }
}

//提示信息
WEBKP.namespace('MsgBar');
WEBKP.MsgBar = function(){
    this.message = "正在载入数据，请稍候……";
    this.refBarObj = $(MainWindow.document.getElementById('pressbar'));
    this.showTime = new Date().getTime();
}
WEBKP.MsgBar.prototype = {
    showMsg: function(msg){
        /*
         this.showTime = new Date().getTime();
         if (msg) {
         this.refBarObj.html(msg);
         }
         else {
         this.refBarObj.html(this.message);
         }
         this.refBarObj.show();
         */
    },
    closeMsg: function(){
        /*
         var usedTime = new Date().getTime() - this.showTime;
         this.showMsg('成功载入,用时' + usedTime / 1000 + 's');
         if (usedTime < 500) {
         var refBar = this.refBarObj;
         window.setTimeout(function(){
         refBar.hide();
         }, 500);
         }
         else {
         this.refBarObj.hide();
         }
         */
    }
}
var MsgBar = new WEBKP.MsgBar();

function copyToClipboard(txt){
    if (window.clipboardData) {
        window.clipboardData.clearData();
        window.clipboardData.setData("Text", txt);
    }
    else 
        if (navigator.userAgent.indexOf("Opera") != -1) {
            window.location = txt;
        }
        else 
            if (window.netscape) {
                try {
                    netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect");
                } 
                catch (e) {
                    return false;
                //alert("被浏览器拒绝！\n请在浏览器地址栏输入'about:config'并回车\n然后将 'signed.applets.codebase_principal_support'设置为'true'");
                }
                var clip = Components.classes['@mozilla.org/widget/clipboard;1'].createInstance(Components.interfaces.nsIClipboard);
                if (!clip) 
                    return false;
                var trans = Components.classes['@mozilla.org/widget/transferable;1'].createInstance(Components.interfaces.nsITransferable);
                if (!trans) 
                    return false;
                trans.addDataFlavor('text/unicode');
                var str = new Object();
                var len = new Object();
                var str = Components.classes["@mozilla.org/supports-string;1"].createInstance(Components.interfaces.nsISupportsString);
                var copytext = txt;
                str.data = copytext;
                trans.setTransferData("text/unicode", str, copytext.length * 2);
                var clipid = Components.interfaces.nsIClipboard;
                if (!clip) 
                    return false;
                clip.setData(trans, null, clipid.kGlobalClipboard);
            }
    
    //alert("复制成功！") ;
    return true;
}

//快盘配置项
WEBKP.namespace('KPConfig');
WEBKP.KPConfig = function(){
    this.dirFolderId = dirFolderId;//当前打开的目录ID,''为根目录
    this.orderFiles = 'name';//当前排序字段
    this.ordType = 'asc';//当前排序方式
    this.View = curview;//默认是外链
    ///////////////////
    this.KpLastUrl = '';//快盘最后一次地址
    this.ToMeLastUrl = '';//收到的共享最后一次地址
    this.OutLastUrl = '';//共享出去的最后一次地址
    this.RcLastUrl = '';//回收站
    this.LinkLastUrl = '';//外链最有一次地址
    ///////////////////
    this.userId = userId;
    this.userEmail = userEmail;
    this.userToken = userToken;
    //////////////////
    this.ufaServer = ufaServer;
    //////////////////
    this.Theme = Theme;
    this.appName = appName;
}
var KpConfig = new WEBKP.KPConfig();

//MenuBar
WEBKP.namespace('MenuBar');
WEBKP.MenuBar = function(){
    this.list = [];
}
WEBKP.MenuBar.prototype = {
    add: function(component){
        this.list.push(component);
    },
    show: function(container){
        this.createMenuHtml(container);
        this.createMenuHtml('contentmenuwrap');
        if(this.count()==0)
        {
            $("#contentmenuwrap").hide();
        }
    },
    createMenuHtml:function(container)
    {
        var ulElement = MainWindow.document.createElement("ul");
        var container = MainWindow.document.getElementById(container);
        $(container).html('');
        for (var i = 0, len = this.list.length; i < len; i++) {
            ulElement.appendChild(this.list[i].getElement());
        }
        container.appendChild(ulElement);
    },
    clear: function(){
        this.list = [];
    },
    count:function()
    {
        return this.list.length;
    }
}
var MenuBar = new WEBKP.MenuBar();

//创建在线转换地址
function createBrowseUrl(fileObj, bigPic){
    var fileName = fileObj.fileName;
    var fileVer = fileObj.fileVer;
    var fileId = fileObj.fileId;
    var pos = fileName.lastIndexOf('.');
    var suff = fileName.substr(pos + 1);
    var isImage = fileObj.isImage;
    if ('1' == isImage) {
        if (bigPic) {
            return [conv_server, '/?f=', fileId, '&v=', fileVer, '&copts=pw:600,h:450&token=',userToken].join('');
        }
        else {
            return [conv_server, '/?f=', fileId, '&v=', fileVer, '&copts=pw:200,h:150&token=',userToken].join('');
        }
    }
    else {
        return [conv_server, '/?f=', fileId, '&v=', fileVer, '&copts=dt:', suff, ',v:normal&token=',userToken,'&ra=1'].join('');
    }
}

//创建在线编辑地址
function createEditUrl(fileId){
    return [wow_server, '?host=www.kuaipan.cn&token=', userToken, '&fileid=', fileId].join('');
}

//创建外链地址
function createOutLinkUrl(fileId){
    if(typeof filelink_multenable == 'undefined'||!filelink_multenable){
        return ['http://www.kuaipan.cn/file/id_', fileId, '.htm'].join('');
    }else{
        return [filelink_domain,'file/id_', fileId, '.htm'].join('');
    }
    //return  ['http://www.kuaipan.cn/index.php?ac=file&oid=',fileId].join('');
}

//格式化右侧预览图片大小
function formatImageSize(imgUrl)
{
    /*
    var img = new Image();
    $(img).load(function(){
        var w = $(this).width();    
        var h = $(this).height();
        if(w>h){
            if(w>203){
                $(this).width(200);
            }
        }else
        {
            if(h>150)
            {
                $(this).height(150);
            }
        }
    }).attr('src',imgUrl);
    */
    //if(imgUrl.indexOf('lottery_fileview.jpg')>0)
    //{
    //    $("#file_preview_wrap").html($('<a href="http://www.kuaipan.cn/index.php?ac=lottery&from=adwangye" target="_blank"></a>').append($(img)));
    //}else{
    //    $("#file_preview_wrap").html($(img));
    //}
}

//createOrderMenu();
//业务处理入口
function CreateMenu(){
    var contObj = $("#filelistwrap").find('tr');
    if(contObj.length==contObj.find('input:checked').length)
    {
        $("#filtercheck").attr('checked',true);
    }else
    {
        $("#filtercheck").attr('checked',false);
    }
    var viewFlag = KpConfig.View;
    switch (viewFlag) {
        case 'KP':
            var selectFile = MainPanelObj.getSelectFile();
            //单个文件，在线查看，在线预览，删除，共享给好友，获取分享链接，历史版本，重命名，移动
            //单个文件夹   删除，共享给好友，重命名，移动
            //多个  删除，移动
            switch (selectFile[2]) {
                case 1:
                    if (selectFile[0] == 1) {
                        var fileId = MainPanelObj.getSelectFilesId();
                        var fileObj = MainPanelObj.getFileInfoByFileId(fileId);
                        if(fileObj.isdel&&'1'==fileObj.isdel)
                        {
                            var recover_menu = new WEBKP.MenuItem("还原", "还原", '', "javascript:;", CommandCenter.getCommand('Recover'),'menu-ico ico-restore');
                            var delete_menu = new WEBKP.MenuItem("删除文件", "删除文件", '', "javascript:;", CommandCenter.getCommand('CleanRecycle'),'menu-ico ico-del');
                            MenuBar.clear();
                            MenuBar.add(recover_menu);
                            MenuBar.add(delete_menu);
                            MenuBar.show('menuwrap');
                        }else
                        {
                            var down_menu = new WEBKP.Menu("下载", "下载", '', "javascript:;", CommandCenter.getCommand('Down'), 'menu-ico ico-down');
                            var delete_menu = new WEBKP.Menu("删除", "删除", '', "javascript:;", CommandCenter.getCommand('Delete'), 'menu-ico ico-del');
                            var move_menu = new WEBKP.MenuItem("移动", "移动", '', "javascript:;", CommandCenter.getCommand('Move'), 'menu-ico ico-move');
                            var share_menu = new WEBKP.Menu("共享给好友", "共享给好友", '', "javascript:;", CommandCenter.getCommand('Share'), 'menu-ico ico-share');
                            var rename_menu = new WEBKP.MenuItem("重命名", "重命名", '', "javascript:;", CommandCenter.getCommand('ReName'), 'menu-ico ico-rename');
                            var browse_outlink_menu = new WEBKP.MenuItem("获取分享链接", "获取分享链接", '', "javascript:;", CommandCenter.getCommand('PublishOutLink'), 'menu-ico ico-outlink');
                            MenuBar.clear();
                            MenuBar.add(down_menu);
                            /*
                            if('1' == fileObj.isCanConvert){
                                var browse_menu = new WEBKP.Menu("在线查看", "在线查看", '', "javascript:;", CommandCenter.getCommand('Browse'), 'menu-ico ico-preview');
                                MenuBar.add(browse_menu);
                            }
                            if('1' == fileObj.isCanWow){
                                var edit_menu = new WEBKP.MenuItem("在线编辑", "在线编辑", '', "javascript:;", CommandCenter.getCommand('Edit'), 'menu-ico ico-edit');
                                MenuBar.add(edit_menu);
                            }
                            //if ('1' != fileObj.fileVer) {
                            //    var history_menu = new WEBKP.MenuItem("历史版本", "历史版本", '', "javascript:;", CommandCenter.getCommand('History'), 'menu-ico ico-history');
                            //    MenuBar.add(history_menu);
                            //}
                            if(fileId==fileObj.shareId||'0' == fileObj.shareId)
                            {
                                MenuBar.add(share_menu);
                            }
                            if(fileId == fileObj.shareId)
                            {
                                var cancel_share = new WEBKP.MenuItem("取消共享", "取消共享", '', "javascript:;", CommandCenter.getCommand('CancelShare'), 'menu-ico ico-share');
                                MenuBar.add(cancel_share);
                            }
                            MenuBar.add(browse_outlink_menu);
                            */
                            MenuBar.add(share_menu);
                            MenuBar.add(rename_menu);
                            //MenuBar.add(move_menu);
                            MenuBar.add(delete_menu);
                            MenuBar.show('menuwrap');
                            /*
                            if ('1' == fileObj.isImage) {//是否是图片
                                var imgurl = createBrowseUrl(fileObj)
                                //$("#file_preview").attr('src', );
                                formatImageSize(imgurl);
                            }
                            else {
                                //$("#file_preview").attr('src', defaultPreview);
                                formatImageSize(defaultPreview);
                            }
                            */
                            $("#defaultOptext").html(CommFormatFileName(fileObj.fileName,25,3));
                        }
                    }
                    else {
                        var fileId = MainPanelObj.getSelectFilesId();
                        var fileObj = MainPanelObj.getFileInfoByFileId(fileId);
                        if(fileObj.isdel&&'1'==fileObj.isdel)
                        {
                            MenuBar.clear();
                            if(currIsNoDel&&currIsNoDel=='1')
                            {
                                var recover_menu = new WEBKP.MenuItem("还原", "还原", '', "javascript:;", CommandCenter.getCommand('Recover'),'menu-ico ico-restore');
                                var delete_menu = new WEBKP.MenuItem("删除文件夹", "删除文件夹", '', "javascript:;", CommandCenter.getCommand('CleanRecycle'),'menu-ico ico-del');
                                MenuBar.add(recover_menu);
                                MenuBar.add(delete_menu);
                            }
                            MenuBar.show('menuwrap');
                            $("#defaultOptext").html(CommFormatFileName(fileObj.fileName,25,3));
                            formatImageSize(defaultPreview);
                        }
                        else
                        {
                            var delete_menu = new WEBKP.Menu("删除", "删除", '', "javascript:;", CommandCenter.getCommand('Delete'), 'menu-ico ico-del');
                            var move_menu = new WEBKP.MenuItem("移动", "移动", '', "javascript:;", CommandCenter.getCommand('Move'), 'menu-ico ico-move');
                            var share_menu = new WEBKP.Menu("共享给好友", "共享给好友", '', "javascript:;", CommandCenter.getCommand('Share'), 'menu-ico ico-share');
                            var rename_menu = new WEBKP.MenuItem("重命名", "重命名", '', "javascript:;", CommandCenter.getCommand('ReName'), 'menu-ico ico-rename');
                            var browse_outlink_menu = new WEBKP.MenuItem("获取分享链接", "获取分享链接", '', "javascript:;", CommandCenter.getCommand('PublishOutLink'), 'menu-ico ico-outlink');
                            var down_menu = new WEBKP.Menu("打包下载", "打包下载", '', "javascript:;", CommandCenter.getCommand('Down'), 'menu-ico ico-down');
                            MenuBar.clear();
                            $("#defaultOptext").html(CommFormatFileName(fileObj.fileName,25,3));
                            //MenuBar.add(down_menu);
                            /*
                            if(fileId==fileObj.shareId||'0' == fileObj.shareId)
                            {
                                MenuBar.add(share_menu);
                            }
                            if(fileId == fileObj.shareId)
                            {
                                var cancel_share = new WEBKP.MenuItem("取消共享", "取消共享", '', "javascript:;", CommandCenter.getCommand('CancelShare'), 'menu-ico ico-share');
                                MenuBar.add(cancel_share);
                            }
                            MenuBar.add(browse_outlink_menu);
                            */
                            MenuBar.add(rename_menu);
                            //MenuBar.add(move_menu);
                            MenuBar.add(delete_menu);
                            MenuBar.show('menuwrap');
                            formatImageSize(defaultPreview);
                        }
                    }
                    break;
                case 0:
                    formatImageSize(defaultPreview);
                    $("#defaultOptext").html(defaultOpText);
                    MenuBar.clear();
                    MenuBar.show('menuwrap');
                    break;
                default:
                    var delFileCount =0,noDelFileCount = 0,selDelFile=0;
                    var fileIds = MainPanelObj.getSelectFilesId();
                    var fileCount = fileIds.length;
                    for(var i =0;i<fileCount;i++)
                    {
                        var fileObj = MainPanelObj.getFileInfoByFileId(fileIds[i]);
                        if(fileObj.isdel&&"1"==fileObj.isdel)
                        {
                            delFileCount++;
                            if('file' == fileObj.fileType)
                            {
                                selDelFile++;
                            }
                        }else
                        {
                            noDelFileCount++;
                        }
                    }
                    if(fileCount==delFileCount)//全部是删除的
                    {
                        var recover_menu = new WEBKP.MenuItem("还原", "还原", '', "javascript:;", CommandCenter.getCommand('Recover'),'menu-ico ico-restore');
                        var delete_menu = new WEBKP.MenuItem("删除文件", "删除文件", '', "javascript:;", CommandCenter.getCommand('CleanRecycle'),'menu-ico ico-del');
                        MenuBar.clear();
                        if(selDelFile==delFileCount){//全部是文件
                            MenuBar.add(recover_menu);
                            MenuBar.add(delete_menu);
                        }else
                        {
                            if(currIsNoDel&&currIsNoDel=='1')
                            {
                                MenuBar.add(recover_menu);
                                MenuBar.add(delete_menu);
                            }
                        }
                        MenuBar.show('menuwrap');
                        formatImageSize(defaultPreview);
                        $("#defaultOptext").html(defaultOpText);
                    
                    }else
                    {
                        if(fileCount==noDelFileCount)//全部是未删除的
                        {
                            var delete_menu = new WEBKP.Menu("删除", "删除", '', "javascript:;", CommandCenter.getCommand('Delete'), 'menu-ico ico-del');
                            var move_menu = new WEBKP.MenuItem("移动", "移动", '', "javascript:;", CommandCenter.getCommand('Move'), 'menu-ico ico-move');
                            MenuBar.clear();
                            MenuBar.add(move_menu);
                            MenuBar.add(delete_menu);
                            MenuBar.show('menuwrap');
                            formatImageSize(defaultPreview);
                            $("#defaultOptext").html(defaultOpText);
                        }else//混合
                        {
                            formatImageSize(defaultPreview);
                            $("#defaultOptext").html(defaultOpText);
                            MenuBar.clear();
                            MenuBar.show('menuwrap');
                        }
                    }
            }
            break;
        case 'TM':
            var selectFile = MainPanelObj.getSelectFile();
            switch (selectFile[2]) {
                case 1:
                    var fileId = MainPanelObj.getSelectFilesId();
                    var fileObj = MainPanelObj.getFileInfoByFileId(fileId);
                    if (selectFile[0] == 1) {
                        var existshare_menu = new WEBKP.Menu("退出共享", "退出共享", '', "javascript:;", CommandCenter.getCommand('ExitShare'),'menu-ico ico-share');
                        var down_menu = new WEBKP.Menu("下载", "下载", '', "javascript:;",CommandCenter.getCommand('Down'),'menu-ico ico-down');
                        MenuBar.clear();
                        MenuBar.add(down_menu);
                        if ('1' == fileObj.isCanConvert) {
                            var browse_menu = new WEBKP.Menu("在线查看", "在线查看", '', "javascript:;", CommandCenter.getCommand('Browse'), 'menu-ico ico-preview');
                            MenuBar.add(browse_menu);
                        }
                        if ('1' == fileObj.isCanWow) {
                            var edit_menu = new WEBKP.MenuItem("在线编辑", "在线编辑", '', "javascript:;", CommandCenter.getCommand('Edit'), 'menu-ico ico-edit');
                            MenuBar.add(edit_menu);
                        }
                        var showExitShare =  (typeof Config_ExistShare == 'undefined')?true:false;
                        if(showExitShare){
                            MenuBar.add(existshare_menu);
                        }
                        if ('1' == fileObj.isImage) {//是否是图片
                            var imgurl = createBrowseUrl(fileObj)
                            //$("#file_preview").attr('src', imgurl);
                            formatImageSize(imgurl);
                        }
                        else {
                            //$("#file_preview").attr('src', defaultPreview);
                            formatImageSize(defaultPreview);
                        }
                        $("#defaultOptext").html(CommFormatFileName(fileObj.fileName,25,3));
                        MenuBar.show('menuwrap');
                    }
                    else {
                        MenuBar.clear();
                        var existshare_menu = new WEBKP.Menu("退出共享", "退出共享", '', "javascript:;", CommandCenter.getCommand('ExitShare'),'menu-ico ico-share');
                        var showExitShare = (typeof Config_ExistShare == 'undefined')?true:false;
                        if(showExitShare){
                            MenuBar.add(existshare_menu);
                        }
                        MenuBar.show('menuwrap');
                        var fileId = MainPanelObj.getSelectFilesId();
                        var fileObj = MainPanelObj.getFileInfoByFileId(fileId);
                        $("#defaultOptext").html(CommFormatFileName(fileObj.fileName,25,3));
                        //$("#file_preview").attr('src', defaultPreview);
                        formatImageSize(defaultPreview);
                    }
                    break;
                case 0:
                    MenuBar.clear();
                    MenuBar.show('menuwrap');
                    //$("#file_preview").attr('src', defaultPreview);
                    formatImageSize(defaultPreview);
                    $("#defaultOptext").html(defaultOpText);
                    break;
                default:
                    MenuBar.clear();
                    MenuBar.show('menuwrap');
                    //$("#file_preview").attr('src', defaultPreview);
                    formatImageSize(defaultPreview);
                    $("#defaultOptext").html(defaultOpText);
            }
            break;
        case 'OU':
            var selectFile = MainPanelObj.getSelectFile();
            switch (selectFile[2]) {
                case 1:
                    if (selectFile[0] == 1) {//一个文件
                        var fileId = MainPanelObj.getSelectFilesId();
                        var fileObj = MainPanelObj.getFileInfoByFileId(fileId);
                        var share_menu = new WEBKP.Menu("共享给好友", "共享给好友", '', "javascript:;", CommandCenter.getCommand('Share'),'menu-ico ico-share');
                       // var existshare_menu = new WEBKP.Menu("取消共享", "取消共享", '', "javascript:;", CommandCenter.getCommand('ExitShare'),'menu-ico ico-de-share');
                        MenuBar.clear();
                        MenuBar.add(share_menu);
                       //MenuBar.add(existshare_menu);
                        if ('1' == fileObj.isCanConvert) {
                            var browse_menu = new WEBKP.Menu("在线查看", "在线查看", '', "javascript:;", CommandCenter.getCommand('Browse'), 'menu-ico ico-preview');
                            MenuBar.add(browse_menu);
                        }
                        if ('1' == fileObj.isCanWow) {
                            //var edit_menu = new WEBKP.MenuItem("在线编辑", "在线编辑", '', "javascript:;", CommandCenter.getCommand('Edit'), 'menu-ico ico-edit');
                           // MenuBar.add(edit_menu);
                        }
                        MenuBar.show('menuwrap');
                        if ('1' == fileObj.isImage) {//是否是图片
                            var imgurl = createBrowseUrl(fileObj)
                            //$("#file_preview").attr('src', imgurl);
                            formatImageSize(imgurl);
                        }
                        else {
                            //$("#file_preview").attr('src', defaultPreview);
                            formatImageSize(defaultPreview);
                        }
                        $("#defaultOptext").html(CommFormatFileName(fileObj.fileName,25,3));
                    }
                    else {
                        var share_menu = new WEBKP.Menu("共享给好友", "共享给好友", '', "javascript:;", CommandCenter.getCommand('Share'),'menu-ico ico-share');
                        //var existshare_menu = new WEBKP.Menu("取消共享", "取消共享", '', "javascript:;", CommandCenter.getCommand('ExitShare'),'menu-ico ico-de-share');
                        MenuBar.clear();
                        var fileId = MainPanelObj.getSelectFilesId();
                        var fileObj = MainPanelObj.getFileInfoByFileId(fileId);
                        $("#defaultOptext").html(CommFormatFileName(fileObj.fileName,25,3));
                        //$("#file_preview").attr('src', defaultPreview);
                        formatImageSize(defaultPreview);
                        MenuBar.add(share_menu);
                        //MenuBar.add(existshare_menu);
                        MenuBar.show('menuwrap');
                    }
                    break;
                case 0:
                    MenuBar.clear();
                    MenuBar.show('menuwrap');
                    //$("#file_preview").attr('src', defaultPreview);
                    formatImageSize(defaultPreview);
                    $("#defaultOptext").html(defaultOpText);
                    break;
                default:
                    MenuBar.clear();
                    MenuBar.show('menuwrap');
                    //$("#file_preview").attr('src', defaultPreview);
                    formatImageSize(defaultPreview);
                    $("#defaultOptext").html(defaultOpText);
            }
            break;
        case 'RC':
            formatImageSize(defaultPreview);
            var selectFile = MainPanelObj.getSelectFile();
            switch (selectFile[2]) {
                case 0:
                    var clearall_menu = new WEBKP.MenuItem("清空回收站", "清空回收站", '', "javascript:;", CommandCenter.getCommand('CleanAllRecycle'),'menu-ico ico-recycle');
                    MenuBar.clear();
                    $("#defaultOptext").html(defaultOpText);
                    if(0!=MainPanelObj.getAllFiles().length){
                        MenuBar.add(clearall_menu);
                    }
                    MenuBar.show('menuwrap');
                    break;
                case 1:
                    var clearall_menu = new WEBKP.MenuItem("清空回收站", "清空回收站", '', "javascript:;", CommandCenter.getCommand('CleanAllRecycle'),'menu-ico ico-recycle');
                    var delete_menu = new WEBKP.MenuItem("删除文件", "删除文件", '', "javascript:;", CommandCenter.getCommand('CleanRecycle'),'menu-ico ico-del');
                    var recover_menu = new WEBKP.MenuItem("还原", "还原", '', "javascript:;", CommandCenter.getCommand('Recover'),'menu-ico ico-restore');
                    MenuBar.clear();
                    MenuBar.add(recover_menu);
                    MenuBar.add(delete_menu);
                    MenuBar.add(clearall_menu);
                    MenuBar.show('menuwrap');
                    var fileId = MainPanelObj.getSelectFilesId();
                    var fileObj = MainPanelObj.getFileInfoByFileId(fileId);
                    $("#defaultOptext").html(CommFormatFileName(fileObj.fileName,25,3));
                    break;
                default:
                    var clearall_menu = new WEBKP.MenuItem("清空回收站", "清空回收站", '', "javascript:;", CommandCenter.getCommand('CleanAllRecycle'),'menu-ico ico-recycle');
                    var delete_menu = new WEBKP.MenuItem("删除文件", "删除文件", '', "javascript:;", CommandCenter.getCommand('CleanRecycle'),'menu-ico ico-del');
                    var recover_menu = new WEBKP.MenuItem("还原", "还原", '', "javascript:;", CommandCenter.getCommand('Recover'),'menu-ico ico-restore');
                    MenuBar.clear();
                    $("#defaultOptext").html(defaultOpText);
                    MenuBar.add(recover_menu);
                    MenuBar.add(delete_menu);
                    MenuBar.add(clearall_menu);
                    MenuBar.show('menuwrap');
            }
            break;
        case 'Link':
            formatImageSize(defaultPreview);
            var selectFile = MainPanelObj.getSelectFile();
            switch (selectFile[2]) {
                case 0:
                    MenuBar.clear();
                    MenuBar.show('menuwrap');
                    break;
                case 1:
                    var fileId = MainPanelObj.getSelectFilesId();
                    if('' != fileId){
                        var browse_outlink_menu = new WEBKP.MenuItem("查看外链", "查看外链", '', "javascript:;", CommandCenter.getCommand('BrowseLink'),'menu-ico ico-query-outlink');
                        var copy_outlink_menu = new WEBKP.MenuItem("复制地址", "复制外链", '', "javascript:;", CommandCenter.getCommand('CopyLink'),'menu-ico ico-copy-outlink');
                        var cancel_outlink_menu = new WEBKP.MenuItem("删除外链", "删除外链", '', "javascript:;", CommandCenter.getCommand('CancelOutlink'),'menu-ico ico-de-outlink');
                        var setpwd_menu = new WEBKP.MenuItem("设置/取消 密码", "设置密码", '', "javascript:;", CommandCenter.getCommand('PublishOutLink'),'menu-ico ico-outlink');
                        MenuBar.clear();
                        MenuBar.add(browse_outlink_menu);
                        MenuBar.add(setpwd_menu);
                        MenuBar.add(copy_outlink_menu);
                        MenuBar.add(cancel_outlink_menu);
                        MenuBar.show('menuwrap');
                        $.ajax({
                            url:'index.php?ac=fileview_handler&op=getiteminfo',
                            dataType:'json',
                            type:'post',
                            data:{'fileId':fileId[0]},
                            success:function(res)
                            {
                                if(res&&"ok"==res.xLive_attr.result)
                                {
                                }else
                                {
                                    var browse_outlink_menu = new WEBKP.MenuItem("查看外链", "查看外链", '', "javascript:;", CommandCenter.getCommand('BrowseLink'),'menu-ico ico-query-outlink');
                                    var copy_outlink_menu = new WEBKP.MenuItem("复制地址", "复制外链", '', "javascript:;", CommandCenter.getCommand('CopyLink'),'menu-ico ico-copy-outlink');
                                    var cancel_outlink_menu = new WEBKP.MenuItem("删除外链", "删除外链", '', "javascript:;", CommandCenter.getCommand('CancelOutlink'),'menu-ico ico-de-outlink');
                                    MenuBar.clear();
                                    MenuBar.add(browse_outlink_menu);
                                    MenuBar.add(copy_outlink_menu);
                                    MenuBar.add(cancel_outlink_menu);
                                    MenuBar.show('menuwrap');
                                }
                            }
                        })
                    }else
                    {
                        MenuBar.clear();
                        MenuBar.show('menuwrap');
                    }
                    break;
                default:
                    var cancel_outlink_menu = new WEBKP.MenuItem("删除外链", "删除外链", '', "javascript:;", CommandCenter.getCommand('CancelOutlink'),'menu-ico ico-de-outlink');
                    MenuBar.clear();
                    MenuBar.add(cancel_outlink_menu);
                    MenuBar.show('menuwrap');
                    break;
            }
    }
}

//handler....
//重命名处理
WEBKP.namespace('ReNameHandler');
WEBKP.ReNameHandler = function(){
    this.panelId = $('#renamepanel');
    this.txtfiled = $("#renamefiled");
    this.oldfileName = $("#oldfileName");
    
}
WEBKP.ReNameHandler.prototype = {
    bntHandler: function(e, _this, fileObj){
        var allFiles = MainPanelObj.getSelectFilesId();
        var itemObj = MainPanelObj.getFileInfoByFileId(allFiles[0]);
        var refFiled = $("#refilename");
        switch (e) {
            case 'close':
            case 'cancel':
                popRef.close();
                break;
            case 'ok':
                var newname = refFiled.val()
                rewname = newname.replace(/\s/ig, '');
                rewname = rewname.toUpperCase();
                var errmsg  ='';
                if (rewname == '') {
                    errmsg = '文件名不能为空';
                }
                if (rewname.length > 255) {
                    errmsg = '文件名长度不能超过255个字符';
                }
                if (newname.indexOf('.') == 0) {
                    errmsg = '文件名不能以.开始';
                }
                if (/["'\/\\\?\*:\<\>\|]+/.test(newname)) {
                    errmsg = '文件名不能包含下列任意字符之一：\n\r\t/\\*:?"<>|';
                }
                if ($.inArray(rewname, ['COM1', 'COM2', 'COM3', 'COM4', 'LPT1', 'LPT2', 'CON', 'AUX', 'PRN', 'NUL']) != -1) {
                    errmsg = '无法重命名为:' + newname;
                }
                if(''!=errmsg)
                {
                    popRef.close();
                    popRef.alert({
                        title: '操作失败',
                        message: errmsg
                    })
                    return false;
                }
                $.ajax({
                    url: 'rename.php',
                    dataType: 'json',
                    data: {
                        'ownerid':  userId,
                        'parentid': dirId,
                        'type': itemObj.fileType,
                        'name': itemObj.fileName,
                        'newname': refFiled.val()
                    },
                    type: 'post',
                    success: function(res){
                        try {
                            var result = res.result
                            switch (result) {
                                case 'ok':
                                    popRef.close();
                                    popRef.succeedInfo({
                                        message: '重命名成功',
                                        title: '操作成功',
                                        width: 270,
                                        height: 150,
                                        handler: function(){
                                            MainPanelObj.refreshFilePanel();
                                        }
                                    })
                                    break;
                                case 'fnameTooLong':
                                    popRef.close();
                                    popRef.alert({
                                        title: '操作失败',
                                        message: '重命名失败，文件名超长'
                                    })
                                    break;
                                case 'targetExist':
                                    popRef.close();
                                    popRef.alert({
                                        title: '操作失败',
                                        message: '重命名失败，该目录下存在相同的名称的文件夹'
                                    })
                                    break;
                                case 'clientBadParams':
                                    popRef.close();
                                    popRef.alert({
                                        title: '操作失败',
                                        message: '重命名失败,请输入文件夹名称'
                                    });
                                    break;
                            }
                        } 
                        catch (e) {
                            popRef.close();
                            popRef.alert({
                                title: '操作失败',
                                message: '对不起，重命名失败'
                            });
                        }
                    },
                    error: function(){
                        popRef.alert({
                            title: '操作失败',
                            message: '对不起，重命名失败'
                        });
                    }
                })
                break;
        }
    },
    doHandler: function(fileObj){
        var _this = this;
        var oldName = fileObj.fileName;
        popRef.confirmInfo({
            icoCls: '',
            msgCls: 'confirm',
            message: '<div class="pop-frm" >重命名：<input type=\'text\' id=\'refilename\' class="pop-txt" onfocus=\'this.select()\' value="' + oldName + '" /></div>',
            title: '重命名',
            
            height: 160,
            handler: function(e){
                _this.bntHandler(e, _this, fileObj);
            },
            autoClose: false
        });
    }
}
var ReNameHandler = new WEBKP.ReNameHandler();
//新建文件夹处理
WEBKP.namespace('NewDirHandler');
WEBKP.NewDirHandler = function(){
    this.panelId = $("#newdirpanel");
    this.newdirfiled = $("#newdirfiled");
    this.confirmbnt = $("#confirmnewdir");
    this.newdirmsg = $("#newdirmsg");
}
WEBKP.NewDirHandler.prototype = {
    bntHandler: function(e, _this){
        var refFiled = $("#newdirname");
        switch (e) {
            case 'close':
            case 'cancel':
                popRef.close();
                break;
            case 'ok':
                if(refFiled.val().length>255)
                {
                    alert('文件夹名长度不能超过255个字符，请重新输入');
                    $("#newdirname").focus();
                    return;
                }
                $.ajax({
                    url: 'mkdir.php',
                    dataType: 'json',
                    data: {
                        'ownerid':  userId,
                        'parentid': dirId,
                        'path': path,
                        'name': refFiled.val()
                    },
                    type: 'post',
                    success: function(res){
                        try {
                            var result = res.xLive_attr.result;
                            switch (result) {
                                case 'ok':
                                    popRef.close();
                                    popRef.succeedInfo({
                                        message: '新建文件夹成功',
                                        title: '操作成功',
                                        width: 270,
                                        height: 150,
                                        handler: function(){
                                            MainPanelObj.refreshFilePanel();
                                        }
                                    })
                                    break;
                                    case "parentNotExist":
                                    popRef.close();
                                    popRef.alert({
                                        title: '操作失败',
                                        message: '新建文件夹失败，目录不存在',
                                    handler:function(){
                                        MainPanelObj.refreshFilePanel();
                                    }
                                    })
                                    break;
                                case 'targetExist':
                                    popRef.close();
                                    popRef.alert({
                                        title: '操作失败',
                                        message: '新建文件夹失败，该目录下存在相同的名称的文件夹'
                                    })
                                    break;
                                case 'clientBadParams':
                                    popRef.close();
                                    popRef.alert({
                                        title: '操作失败',
                                        message: '新建文件夹失败,请输入文件夹名称'
                                    });
                                    break;
                            }
                        } 
                        catch (e) {
                            popRef.close();
                            popRef.alert({
                                title: '操作失败',
                                message: '对不起，新建文件夹失败'
                            });
                        }
                    },
                    error: function(){
                        popRef.alert({
                            title: '操作失败',
                            message: '对不起，新建文件夹失败'
                        });
                    }
                })
                break;
        }
        
    },
    doHandler: function(fileName){
        var _this = this;
        popRef.confirmInfo({
            msgCls: 'confirm',
            message: '<div class="pop-frm"><label>新文件夹名称：</label><input type=\'text\' id=\'newdirname\' class="pop-txt" onfocus=\'this.select()\' value="' + fileName + '" /></div>',
            title: '请输入文件夹名称',
            height: 155,
            width: 350,
            handler: function(e){
                _this.bntHandler(e, _this);
            },
            autoClose: false
        });
    }
}
var NewDirHandler = new WEBKP.NewDirHandler();

//移动跟还原
WEBKP.namespace('MoveRecover');
WEBKP.MoveRecover = function(){
    this.panelObj = $('#movepanel');
    this.treeObj = $('#movetomenu');
    this.fileBoxObj = $("#boxmovefile");
    this.panelTitle = "移动";//可以是还原
    this.operatetitle = $("#operatetitle");
    this.operateloc = $("#operateloc");
    this.fileList = [];
}
WEBKP.MoveRecover.prototype = {
    showPanel: function(fileList, op){//op 为 move 或者 recover
        var opflag = op || 'move';
        if (opflag == 'move') {
            this.panelTitle = "移动";
            this.operatetitle.html('移动的文件（夹）');
            this.operateloc.html('选择移动到的位置');
        }
        else {
            this.panelTitle = "还原"
            this.operatetitle.html('还原的文件');
            this.operateloc.html('选择还原到的位置');
        }
        var selfObj = this;
        var refPanel = selfObj.panelObj;
        var panelTitle = selfObj.panelTitle;
        var treeObj = selfObj.treeObj;
        popRef.win({
            title: '移动文件（夹）',
            fixPosition: true,
            width: 500,
            height: 350,
            maxBtn: false,
            minBtn: false,
            iframe:{id:'dfd',name:'dserered',src:'index.php?ac=fileview_handler&op=moveview'},
            message:'',
            btn: [['确定', 'yes'], ['取消', 'cancel']],
            handler: function(e){
                switch (e) {
                    case 'yes':
                        var moveLocId = popRef.getPage().contentWindow.getMoveLoc();
                        if (moveLocId && '' != moveLocId) {
                            $.ajax({
                                url: 'index.php?ac=fileview_handler&op=move',
                                dataType: 'json',
                                type: 'post',
                                data: {
                                    parentid: moveLocId,
                                    fileid: MainPanelObj.getSelectFilesId()
                                },
                                success: function(res){
                                    if (res) {
                                        var succsum = 0, errsum = 0, len = res.length;
                                        var okFileList = [];
                                        for (var i = 0; i < len; i++) {
                                            if ('ok' == res[i].result) {
                                                $("#tr" + res[i].fileId).remove();
                                                okFileList.push(res[i].fileId);
                                                succsum++;
                                            }
                                            else {
                                                errsum++;
                                            }
                                        }
                                        MainPanelObj.refreshFilePanel('delete', okFileList);
                                        if (succsum == len) {
                                            popRef.succeedInfo({
                                                title: '操作结果',
                                                message: ['操作成功，成功移动', succsum, '项'].join('')
                                            });
                                        }
                                        else {
                                            popRef.alert({
                                                title: '操作结果',
                                                message: ['成功移动', succsum, '项,失败', errsum, '项'].join('')
                                            });
                                        }
                                    }
                                }
                            })
                        }
                        break;
                    case 'cancel':
                    case 'close':
                        popRef.close();
                        break;
                }
            }
        })
        selfObj.loadSelectFile(fileList);
    },
    loadSelectFile: function(selectData){
        var html = [];
        var refBox = this.fileBoxObj;
        this.fileList = [];
        for (var i = 0, len = selectData.length; i < len; i++) {
            var fileId = selectData[i].fileId;
            this.fileList.push(fileId);
            var fileName = selectData[i].fileName;
            var fileType = 'tree-folder';
            if (selectData[i].fileType == 'file') {
                fileType = 'tree-file';
            }
            html.push('<div title="', fileName, '"><ins class="', fileType, '"></ins><span class="movefilename">', fileName, '</span></div>');
        }
        refBox.html('<div class="movefilewrap">' + html.join('') + '</div>');
    },
    doHandler: function(op){
        var refTree = this.treeObj;
        var selectNode = refTree.tree('getSelected');
        var fileList = this.fileList;
        var refPanel = this.panelObj;
        var opUrl = (op == 'move') ? 'edit/move/' : 'rc/recover/';
        if (selectNode) {
            var fid = selectNode.id;
            fid = (fid == 'root') ? '' : fid;
            if (fileList.length > 0) {
                $.ajax({
                    url: opUrl,
                    type: 'post',
                    dataType: 'json',
                    data: {
                        fileId: fileList,
                        parendId: fid
                    },
                    success: function(data){
                        if (undefined != data && undefined != data.result && undefined != data.result.value && 'ok' == data.result.value) {
                            refPanel.parent('div').fadeOut("slow", function(){
                                refPanel.dialog('close');
                            });
                            if (op == 'move') {
                                refTree.tree('reload');
                            }
                            MainPanelObj.refreshFilePanel();
                        }
                        else {
                            if (op == 'move') {
                                $.messager.alert('移动文件', '移动文件（夹）失败!', 'info');
                            }
                            else {
                                $.messager.alert('还原文件', '还原文件失败!', 'info');
                            }
                        }
                    }
                });
            }
            else {
                $.messager.alert('提示', '您没有选择任何文件或者文件夹!', 'info');
            }
        }
        else {
            if (op == 'move') {
                $.messager.alert('提示', '请选择移到的位置!', 'info');
            }
            else {
                $.messager.alert('提示', '请选择还原的位置!', 'info');
            }
        }
    }
}
var MoveRecover = new WEBKP.MoveRecover();
//排序处理
WEBKP.namespace('OrderHandler');
WEBKP.OrderHandler = function(){
}
WEBKP.OrderHandler.prototype = {
    urlFormat: function(url){
        var orderFiles = KpConfig.orderFiles;
        var ordType = KpConfig.ordType;
        if (url.indexOf('?') == -1) {
            url = url + '?';
        }
        url = url.replace(/orderFiles=[^&]*/, ('orderFiles=' + orderFiles));
        if (url.indexOf('orderFiles=') == -1) {
            url = url + '&orderFiles=' + orderFiles;
        }
        url = url.replace(/ordType=[^&]*/, ('ordType=' + ordType));
        if (url.indexOf('ordType=') == -1) {
            url = url + '&ordType=' + ordType;
        }
        return url;
    },
    doHandler: function(){
        var view = KpConfig.View;
        var url = '';
        switch (view) {
            case 'KP':
                url = KpConfig.KpLastUrl;
                break;
            case "TM":
                url = KpConfig.ToMeLastUrl;
                break;
            case 'OU':
                url = KpConfig.OutLastUrl;
                break;
            case 'RC':
                url = KpConfig.RcLastUrl;
                break;
            case 'Link':
                url = KpConfig.LinkLastUrl;
                break;
        }
        var accessUrl = this.urlFormat(url);
        ContentWindow.location.href = accessUrl;
    },
    getOrderTitle: function(orderKey){
        var orderTitle = '';
        switch (orderKey) {
            case 'name':
                orderTitle = '按名称';
                break;
            case 'time':
                orderTitle = '按时间';
                break;
            case 'size':
                orderTitle = '按大小';
                break;
            case 'email':
                orderTitle = '按邮箱';
                break;
            default:
                orderTitle = '按名称';
        }
        return orderTitle;
    }
}
var OrderHandler = new WEBKP.OrderHandler();

//外链处理
WEBKP.namespace('OutLinkHandler');
WEBKP.OutLinkHandler = function(){
    this.statesNode = $("#outlinkopresult");
    this.nameNode = $("#outlinkfilename");
    this.outLinkWrap = $("#puboutlinkwrap");
}
WEBKP.OutLinkHandler.prototype = {
    disablePanel:function(fileObj)
    {
        popRef.win({
            title: '分享链接升级维护',
            fixPosition: true,
            width: 430,
            height:235,
            message:'<div class="ti28 n">'+outlinkdismsg+'</div>',
            btn:[['关 闭','ok']]
        })
    },
    showPanel: function(fileObj){
        var _this = this;
        var fileId = fileObj.fileId;
        var fileType = fileObj.fileType;
        //if(typeof outlinkflag !='undefined'&&'1'==outlinkflag)
        {
            _this.disablePanel(fileObj);
            return;
        }
        $.ajax({
            url:'index.php?ac=outlink&op=filepickupcode',
            dataType:'json',
            type:'post',
            data:{olid:fileId,ftype:fileType},
            success:function(res)
            {
                if(res&&res.xLive_attr&&"ok" == res.xLive_attr.result)//是外链
                {
                    var pickupCode = res.xLive.pickupCode;
                    pickupflag = (pickupCode.length>0)?"1":"0";
                    popRef.win({
                        title: (ResetTitle||'发布分享链接 - ') + fileObj.fileName,
                        fixPosition: true,
                        width: 460,
                        height: ("0"==pickupflag)?285:315,
                        iframe: {
                            id: 'outlinkpaenl',
                            name: 'outlinkwindow',
                            src: 'index.php?ac=outlink&op=repuboutlink&fileid=' + fileId+"&pickupflag="+pickupflag
                        },
                        autoClose:false,
                        btn: [['确定', 'yes'], ['关闭', 'cancel']],
                        handler: function(e){
                            switch (e) {
                                case 'yes':
                                    var pickUpCode = popRef.getPage().contentWindow.getPickupCode();
                                    var cancelpwd = popRef.getPage().contentWindow.getCancelPwd();
                                    var checkcode = popRef.getPage().contentWindow.getCheckCode();
                                    if("1"==pickupflag&&!cancelpwd)
                                    {
                                        popRef.close();
                                        return;
                                    }
                                    if("0"==pickupflag&&"no"==pickUpCode)
                                    {
                                        popRef.close();
                                        return;
                                    }
                                    if(""==checkcode)
                                    {
                                        alert('请输入验证码');
                                        return;
                                    }else
                                    {
                                        popRef.close();
                                    }
                                    $.ajax({
                                        url:'index.php?ac=fileview_handler&op=publishoutlink&resetpwd=yes',
                                        type:'post',
                                        dataType:'json',
                                        data:{'fileId':fileId,'checkcode':checkcode,'pickupcode':pickUpCode,'fileType':fileType},
                                        success:function(res)
                                        {
                                            if(res&&res.result)
                                            {
                                                if('CheckCodeError'==res.result)
                                                {
                                                    popRef.errorInfo({'title':(ResetTitle||'发布分享链接 - ') + fileObj.fileName,'message':'分享链接失败，验证码错误'});
                                                }
                                                else
                                                {
                                                    popRef.win({
                                                        fixPosition: true,
                                                        width: 460,
                                                        height: 280,
                                                        btn:[['确定','ok']],
                                                        'title':(ResetTitle||'发布分享链接 - ') + fileObj.fileName,
                                                        'message':'',
                                                        iframe:{
                                                            id: 'puboutlinksuccess',
                                                            name: 'puboutlinksuccess',
                                                            src: 'index.php?ac=fileview_handler&op=publishresult&result=ok&resetpwd=yes&pickupcode='+res.pickupcode+'&fileid=' + fileId+'&apiresult='+res.apiresult
                                                        },
                                                        handler:function(e)
                                                        {
                                                            if(typeof publisholcallback != 'undefined')
                                                            {
                                                                publisholcallback();
                                                            }
                                                        }
                                                        });
                                                }
                                            }else
                                            {
                                                popRef.win({
                                                    fixPosition: true,
                                                    width: 460,
                                                    height: 230,
                                                    btn:[['确定','ok']],
                                                    handler:function(e)
                                                    {
                                                        if(typeof publisholcallback != 'undefined')
                                                        {
                                                            publisholcallback();
                                                        }
                                                    },
                                                    'title':(ResetTitle||'发布分享链接 - ') + fileObj.fileName,'message':'',iframe:{
                                                    id: 'puboutlinkfaile',
                                                    name: 'puboutlinkfaile',
                                                    src: 'index.php?ac=fileview_handler&op=publishresult&resetpwd=yes&result=err&fileid=' + fileId+'&apiresult='+res.apiresult
                                                }});
                                            }
                                        }
                                    })
                                    break;
                                case 'cancel':
                                    popRef.close();
                                    break;
                                case 'close':
                                    popRef.close();
                                    break;
                            }
                        }
                    })
                }else
                {
                    popRef.win({
                    title: (ResetTitle||'发布分享链接 - ') + fileObj.fileName,
                    fixPosition: true,
                    width: 460,
                    height: 255,
                    iframe: {
                        id: 'outlinkpaenl',
                        name: 'outlinkwindow',
                        src: 'index.php?ac=fileview_handler&op=publishoutlinkview&fileid=' + fileId
                    },
                    autoClose:false,
                    btn: [['确认发布', 'yes'], ['关闭', 'cancel']],
                    handler: function(e){
                        switch (e) {
                            case 'yes':
                                var pickUpCode = popRef.getPage().contentWindow.getSetPwd();
                                var checkcode = popRef.getPage().contentWindow.getCheckCode();
                                if(""==checkcode)
                                {
                                    alert('请输入验证码');
                                    return;
                                }else
                                {
                                    popRef.close();
                                }
                                $.ajax({
                                    url:'index.php?ac=fileview_handler&op=publishoutlink&resetpwd=no',
                                    type:'post',
                                    dataType:'json',
                                    data:{'fileId':fileId,'checkcode':checkcode,'pickupcode':pickUpCode,'fileType':fileType},
                                    success:function(res)
                                    {
                                        if(res&&res.result)
                                        {
                                            if('CheckCodeError'==res.result)
                                            {
                                                popRef.errorInfo({'title':(ResetTitle||'发布分享链接 - ') + fileObj.fileName,'message':'分享链接失败，验证码错误'});
                                            }
                                            else
                                            {
                                                popRef.win({
                                                    fixPosition: true,
                                                    width: 460,
                                                    height: 280,
                                                    btn:[['确定','ok']],
                                                    handler:function(e)
                                                    {
                                                        if(typeof publisholcallback != 'undefined')
                                                        {
                                                            publisholcallback();
                                                        }
                                                    },
                                                    'title':(ResetTitle||'发布分享链接 - ') + fileObj.fileName,'message':'',iframe:{
                                                    id: 'puboutlinksuccess',
                                                    name: 'puboutlinksuccess',
                                                    src: 'index.php?ac=fileview_handler&op=publishresult&resetpwd=no&result=ok&fileid=' + fileId+'&pickupcode='+res.pickupcode+'&apiresult='+res.apiresult
                                                }});
                                            }
                                        }else
                                        {
                                            popRef.win({
                                                fixPosition: true,
                                                width: 460,
                                                height: 200,
                                                btn:[['确定','ok']],
                                                handler:function(e)
                                                {
                                                    if(typeof publisholcallback != 'undefined')
                                                    {
                                                        publisholcallback();
                                                    }
                                                },
                                                'title':(ResetTitle||'发布分享链接 - ') + fileObj.fileName,'message':'',iframe:{
                                                id: 'puboutlinkfaile',
                                                name: 'puboutlinkfaile',
                                                src: 'index.php?ac=fileview_handler&op=publishresult&resetpwd=no&result=err&fileid=' + fileId+'&apiresult='+res.apiresult
                                            }});
                                        }
                                    }
                                })
                                break;
                            case 'cancel':
                                popRef.close();
                                break;
                            case 'close':
                                popRef.close();
                                break;
                        }
                    }
                });
                    
                }
            }
        })
    },
    doCancelOutlinkHandler: function(allFiles){
        var len = allFiles.length;
        popRef.confirmInfo({
            'title': '取消外链',
            message: '您确实要取消这' + len + '项的外链吗？',
            handler: function(e){
                switch (e) {
                    case 'close':
                        popRef.close();
                        break;
                    case 'ok':
                        $.ajax({
                            url: 'index.php?ac=outlink&op=deleteOutlink',
                            type: 'post',
                            dataType: 'json',
                            data: {
                                fileId: allFiles
                            },
                            success: function(res){
                                MainPanelObj.refreshFilePanel('delete', allFiles);
                            }
                        })
                        break;
                }
            }
        })
    }
}
var OutLinkHandler = new WEBKP.OutLinkHandler();


//命令中心,管理命令对象，当存在命令不再需要new
WEBKP.namespace('CommandCenter');
WEBKP.CommandCenter = function(){
    this.commandList = ['Create', 'Share', 'ExitShare', 'CancelShare', 'Upload', 'Delete', 'History', 'Edit', 'Browse', 'Move', 'Recover', 'CleanRecycle', 'CleanAllRecycle', 'ReName', 'Clean', 'Down', 'PublishOutLink', 'CancelOutlink', 'BrowseLink', 'CopyLink'];
}
WEBKP.CommandCenter.prototype = {
    handler: function(comandName, fileId){
        if ($.inArray(comandName, this.commandList) != -1) {
            var command = new WEBKP['on' + comandName + 'Command'](fileId);
            command.execute();
        }
    },
    getCommand: function(commandName){
        if ($.inArray(commandName, this.commandList) != -1) {
            if (this[commandName]) {
                return this[commandName];
            }
            else {
                this[commandName] = new WEBKP['on' + commandName + 'Command']();
                return this[commandName];
            }
        }
    },
    execBefore:function()//命令执行前
    {
        $("#contentmenuwrap").hide();
    }
}
var CommandCenter = new WEBKP.CommandCenter();

$(function()
{
    $('#uploadbnt').click(function(){
        CommandCenter.getCommand('Upload').execute();
    });
    
    $("#newdirbnt").click(function(){
        CommandCenter.getCommand('Create').execute();
    });
    $("#filelistwrap").bind('contextmenu',function(e)
    {
        var obj = $(e.target).closest("tr", $("#filelistwrap")).not('.ui-selected');
        if (obj.length !== 0){
            MainPanelObj.clearSelectFilesId();
            $("#filelistwrap").find('input:checked').attr('checked',false);
            $("#filelistwrap").find(".ui-selected").removeClass('ui-selected');
            MainPanelObj.updateSelectFile(obj.attr('filetype'), obj.attr('fileid'),true);//进入
            obj.find('input').attr('checked',true);
            obj.addClass('ui-selected');
            CreateMenu();
        }
        if(MenuBar.count()>0)
        {
            $("#contentmenuwrap").css({
                    left: e.pageX,
                    top: e.pageY
            }).show();
        }
        $.get("/count.php?ac=contextmenu",{url:location.href});
        return false;
    });
    $(document).bind('contextmenu',function()
    {
        $("#contentmenuwrap").hide();
    });
    
    $(".datatable").selectable({
        cancel: 'a,.list-chk,#headertr',
        filter: '#filelistwrap tr',
        start:function(){
            $("#contentmenuwrap").hide();
        },
        stop:function(){
            MainPanelObj.clearSelectFilesId();
            $("#filelistwrap").find('input:checked').attr('checked',false);
            $(".ui-selected", this).each(function() {
                var obj = $(this);
                MainPanelObj.updateSelectFile(obj.attr('filetype'), obj.attr('fileid'),true);//进入
                obj.find('input').attr('checked',true);
            });
            CreateMenu();
        }
    });
    
});